When jQuery .attr('onclick') function return a event object?

荒凉一梦 提交于 2019-12-12 02:39:06

问题


I am just debugging jQuery in FireBug and wonderig about the return value of

$('.a-selector').attr('onclick');

It turns out to be an onclick(event), but I have read some code before and the author just uses it like this:

$('.a-selector').attr('onclick').replace(..., ...);

which means it can be treated as a String Object. But it reports an error when I use like this.

My jQuery version is 1.5.2. So I wonder when the jQuery changes the API and what is the best way to change the onclick event defined in the HTML.


回答1:


When jQuery .attr('onclick') function return a event object?

In jQuery < 1.6. That's because prior to 1.6, .attr() did a mix between retrieving properties and attributes where it saw fit, newer versions removed that layer of witchery and now have proper methods for retrieving attributes (.attr) and properties (.prop).

Here's a fiddle demonstrating the above.

ps. BTW, it doesn't return an event object, but rather a function object that serves as event handler. =]


Also, 2 side notes: You should always upgrade your jquery to the latest version when viable (currently 1.8.3), it comes with more features, better performance and lots of bug fixes.

And you shouldn't really be using onclicks when you have jQuery, that goes against the Web 2.0 standards of separation of structure (html) and behavior (js) - jQuery itself provides cross-browser handler attaching with the methods .on() (for jQuery 1.7+), and .bind/.delegate/.live for older versions.




回答2:


I assume that you want to change the value of your onclick attribute of some element.

$('.a-selector').attr('onclick',''); // leave 2nd parameter blank if you want to remove its value

OR

$('.a-selector').attr('onclick','myfunc()');
############################### Edit

You can define your function as below :

<script>
    function myfunc(){
        // Do stuff here
    }
</script>



回答3:


is it a possibility for you to reset the click event?

$('.a-selector').unbind('click').click(function() {
    // new function
});

to replace text in an javascript-code is normally not that what javascript should do. I think there is a much better solution possible.



来源:https://stackoverflow.com/questions/13933073/when-jquery-attronclick-function-return-a-event-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!