简体   繁体   English

jQuery on()方法-哪种使用方式对性能更好?

[英]jQuery on() method - which way to use is better for performance?

Is it better to attach the on() event to the document or a closer parent? 将on()事件附加到文档或更紧密的父级更好吗?

Note : Initially this question had another aspect and a different topic. 注意 :最初,此问题涉及另一个方面和另一个主题。 It became obsolete really quickly (typo in the source code) 它很快就过时了(源代码中的典型错误)

The best key for performance using jQuery is to use an id as the initial identifier. 使用jQuery的最佳性能关键是使用id作为初始标识符。 For example: 例如:

$('#my_id').on('click', 'tag.my_class', function () {
    ...
});

This allows jQuery to go straight to the container, and then begin trawling from there. 这允许jQuery直接进入容器,然后从那里开始拖网。

if you bind the "on" event to the closest parent will produce exactly what are you looking for, click function will works fine even if it is appended to document, but in future if you append any elements with class "clickable" will also get binded. 如果将“ on”事件绑定到最接近的父级,将完全生成您要查找的内容,即使附加到文档中,click函数也可以正常工作,但是将来如果您将任何元素添加为“ clickable”类,也会得到绑定。 so its always good practice to append the "on" event to closest parent rather than whole document. 因此,将“ on”事件附加到最接近的父对象而不是整个文档始终是一个好习惯。

if you want more specific you can use 如果您想更具体,可以使用

$("ul.media-grid").on('click', 'li.clickable', function () {
  alert("works")
});

as it will get the ul with the class "media-grid" and appends the event to the li's with class "clickable" 因为它将获得带有“ media-grid”类的ul,并将事件附加到带有“ clickable”类的li的事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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