This works just fine in jQuery 1.6.4 for dynamic html:
$(".selector").die().live("click", function () {
alert("clicked");
});
but I noticed in jQuery 1.7.1 that .live() is deprecated and replaced by .on(). How can I use .on() with dynamic html? Using .die().on("click", function()) doesn’t work and neither does .off().on("click", function()).
Thanks!
The new
onmethod works in much the same way thatdelegatedid in older versions of jQuery. You need to use it on an ancestor element and supply a selector. Since DOM events bubble up from the target, they will eventually reach the ancestor element you have usedonon. When the event reaches that element, the target is checked to see if it matches your selector. If so, the event handler is executed:There has been no need to use
livesincedelegatewas added, some time around version 1.4. Usingdelegatethe above snippet would be:delegateandonare far more efficient thanlive, sincelivealways binds event handlers to thedocument. That means every single event triggered on the page has to be tested to see if it matches the selector and should therefore cause an event handler to run. Withon, only events that bubble to the ancestor element will require this check.