简体   繁体   中英

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>

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>

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.

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", "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM