Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - jQuery on() method on multiple selectors

Since version 1.7 live is deprecated.

Following example is easy to make compatible with new on method:

$('nav li, #sb-nav li, #help li').live('click', function () {
    // code...
});

Using on:

$('nav, #sb-nav, #help').on('click', 'li', function () {
    // code...
});

How to rewrite following example using on?

 $('#header .fixed-feedback-bn, #sb-sec .feedback-bn').live('click', function () {
     // code...
 });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$(document).on('click', '#header .fixed-feedback-bn, #sb-sec .feedback-bn', function () {
     // code...
 });

.live() is just binding document as listener.

My two cents are that you can almost always find a better listener than document. At bare minimum, almost all pages use a main content wrapper. This eliminates nodes in the header, footer, and sometimes sidebars as listeners.

The best way to use .on as a delegating function is to identify the nearest common ancestor that is expected to never be destroyed or otherwise have events unbound. For example, if you have a form that gets updated and changed by ajax requests, the listener could be the form node itself (if only the contents of the form are updated) or a container element (generally a div) that surrounds the form. If such a div isn't there, you could always add it in, or you could just go up the tree to the next ancestor.

[edited to add:]

In the particular sample code provided, it's hard to say if there's a better listener that would contain both #header and also #sb-sec. But imagining that these things share an ancestor with the id "mainContainer", your more efficient code simply swaps out the listener:

$('#mainContainer').on('click', '#header .fixed-feedback-bn, #sb-sec .feedback-bn', function () {
   // code...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...