简体   繁体   中英

jQuery .on efficiency

Is the first .on function more efficient than second one ?

$( "div.container" ).on( "click", "p", function(){
});

$( "body" ).on( "click", "p", function(){
});

Regards

From the jQuery documentation itself about jQuery: .on() :

jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events. So, "#myForm", "a.external", and "button" are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $( "body" ).on( "click", "#commentForm .addNew", addComment ) use $( "#commentForm" ).on( "click", ".addNew", addComment ).

The narrower the first selector is, the better the performance is.

But the first example won't work I guess, because you are monitoring all the <p> s container in <p> s having container class, and a <p> cannot contain another <p> , due to being a phrasing content .

当然,因为浏览器只需监视一个段落的点击事件而不是整个页面。

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