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
406 views
in Technique[技术] by (71.8m points)

jquery - .live() vs .on() method

I'm working on a project, in which when I keep pressing on the min/plus button without hovering off the picture with the .live() method, the function works. In the case of .on() method the function does not work.

How can I fix this issue, so it works for .on() method as well?

Here is an example of what I’m referring too (I fixed the error in this example, but I was using the .on method wrong).

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're not using it correctly. The replacement for .live() is $(document).on() with the event and handler being passed in, of course... for example:

$(document).on('click', '#myElement', function() { 
  //... some function ...
});

It's worth mentioning that before .on() ever came around, .live() was already considered an inefficient way to handle this kind of binding. .delegate() was recommended instead, and now .on() (using the delegator syntax).

Or as an example: instead of the document being the listener (which is what .live() used to do), you should pick the nearest ancestor that does not get destroyed with DOM manipulations. I honestly find the "jsdo.it" a bit clunky to use so I don't have the specific element in mind, but for example, given the structure:

<div id="ajax_container">
 <button id="do_something">Clicky!</button>
 <p>Some dynamically-loaded content</p>
</div>

Where the contents of ajax_container are replaced by an Ajax call (no need to show the code for that part), binding a non-destroyed listener (the container div) for that button's click event would look like:

$('#ajax_container').on('click', '#do_something', function() {
 // do something
})

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

...