开发者

how do we change onclick function via .attr() in jquery?

i got this url

<a class="remove_item' rel="4" onclick="javascript:jQuery(#blablabla)" href="javascript:;' >remove</a> 

i'm using this simple find and replace 开发者_运维技巧

item.find('a.remove_class').attr({
title:'hello',
click:'hello();'
} );

but it seem it's not working. i still not able to replace javascript:jQuery(#blablabla) with another function.


To set onClick you should use something like this $("a").attr("onclick", js);

where js is a string containing your javascript code.


Try attaching the event handler using the below code snippet in your page body:

<script type="text/javascript" language="javascript">
    $(document).ready(function() {
        $('.remove_item').click(hello);
    });
</script>


jQuery has no built-in way to assign event handlers in that way. Use the DOM0 method to set the onclick handler instead:

item.find('a.remove_class').each(function() {
    this.onclick = function() {
        alert("Clicked!");
    };
});

Also, don't put javascript: in you event handler attributes. It's incorrect and only works by coincidence.


Why not just do this.

<script type="text/javascript">
    $(document).ready(function() {
        $("a.remove_item").click(function() {
            alert("You have clicked my <a>!!");
            //do other stuff
        });
    });
</script>


The attr doesn't recognises the onclick attribute, get the html element (.get(0)) and use "raw" functions to extract the onclick attribute.

On Firefox the following works:

$("element").get(0).getAttribute("onclick")

You can remove by using

$("element").get(0).removeAttribute("onclick")

or setting a empty string

$("element").get(0).setAttribute("onclick", "")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜