Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 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 Answer

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
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...