I am curious why when I replace .live() with .on() my events don’t work after inserting AJAX’s response via html() method. Assume I have html structure:
<div class="a">
<a href="" class="alert-link">alert</a>
<a href="" class="ajax-update">update</a>
</div>
and jQuery code something like:
$('.alert-link').on("click", function(){
alert('abc');
return false;
});
and ajax-update will trigger request, which response will be:
alert
update
and I will insert it into parent(). Then pressing again alert-link will result in redirecting to / but if I change .on() to .live() then again alert will be shown. What am I missing here? I have read that .on() is replacement both for .delegate() and .live().
.oncombines and replaces.bind,.live, and.delegate. The syntax$('selector').on('event', callback)is the moral equivalent ofbind, notlive.Add a filtering selector to your call to
on:In this case,
This was changed because it is more efficient to attach a delegate handler to a more localized container element than the old
.livestyle of attaching the handler to the root of the DOM.In other words, even though
alert-linkelements will only appear inside of a smalladiv, with.live, jQuery listens to every single click event on the page and compares it to the delegated selector. By being more targeted, jQuery only has to process clicks on elements withina.