JQuery 'on' vs 'live'

I have a scenario where jQuery 'on' and 'live' do not work the same way. Perhaps someone can indicate why. I am using jQuery 1.7.2 with my project, and in this assembly "live" is replaced by 'on'. I am using the following code on a list page. Basically, this page has an alphabetical panel that the user can click and download all clients with this last name. I would like the link to be done via ajax.

the code:

$("a.listajax").on("click", function (e) { e.preventDefault(); var url = $(this).attr("href"); $("div.content").load(url + " div.content"); return false; }); 

The problem here is that when I first load the page and click the link, everything works fine. The page loads through ajax. However, after that, all links lose their bindings, and then if I click on any links, I get the entire page load.

I replaced 'on' with "live", and the links began to behave perfectly, even with subsequent clicks.

What am I missing?

+4
source share
2 answers

Don't just replace .live with .on .

 $("a.listajax").live('click', function(e)) 

It is equivalent to:

 $(document).on('click', 'a.listajax', function(e)) 

Attention!

If there is a common ancestor for all of your .listajax anchors that will not be removed from the DOM, you should use this (the deepest possible) instead of document ; this will improve performance.

+7
source

That the whole point is live() . It restores new DOM elements when they are created. There are many similar questions on the jQuery site, like this one , because it can be a bit confusing.

According to jQuery docs, you use live() to:

Attach an event handler for all elements that match the current selector, now and in the future.

The "... in the future" part is key because on() does not have this .

+1
source

All Articles