开发者

jQuery: is element.click(func) or element.attr('onclick','func()') more efficient?

开发者 https://www.devze.com 2022-12-28 08:17 出处:网络
I\'m populatin开发者_高级运维g a list by cloning elements into it. Then I change attrs to make each item unique. They need to call a function on click, so I\'m wondering if it\'s more efficient to use

I'm populatin开发者_高级运维g a list by cloning elements into it. Then I change attrs to make each item unique. They need to call a function on click, so I'm wondering if it's more efficient to use new_element.click(func); or new_element.attr('onlick','func();');


new_element.attr('onclick','func();');

Is:

  • inefficient (needlessly creating a new inline function from a string, that does nothing except call func and lose the this reference);

  • aggravating to put any complex code in, since it all has to be JS string escaped;

  • broken in IE, due to bugs in setAttribute.

Avoid. click()/bind('click') is there for a reason.


onclick has a number of limitations, including cluttering the DOM and only allowing one function at a time. So you should use click. See Quirks Mode for more information.


Directly referencing the function will be more efficient than having to interpret a string.

The lowest touch way of doing this, however, is this way:

$(links_selector).live('click', func);

links_selector will presumably be something like ul.listClass a.actionClass. This will not require anything to be done when new list elements get added.


Since you are using jQuery then make it this way

new_element.click(function(){
    // your code
});

or you can bind the click event handler like

new_element.bind("click", function(){
    // your code
});


Any difference in performance between the two is most likely going to be negligible. You should use the one that reads better, and that's element.click. (Plus, onclick has many disadvantages, as @Matthew Flaschen mentioned.)

0

精彩评论

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