I understand that the “live” function is now deprecated. How can I migrate the following to make use of the new “on”?
$('a.action').live( "click", function (evt) {
// Do stuff
}
The scenario is that the a.action is being created on the fly. I’ve tried this, to no avail:
$('a.action').on( "click", function (evt) {
// Do stuff
}
If you want the actual
.live()– type performance wherea.actionobjects don’t have to exist yet when you add the event handler, then you should find a parent DOM object of alla.actionelementss that always exists and bind.on()to that like this:That parent should be as close to the
a.actionobjects as possible for maximum efficiency. For that reason, it is NOT desirable to bind todocument.In fact, one reason
.live()has been deprecated is because it was bound to thedocumentobject and could easily lead to performance problems when there were too many events all flowing through the one object (event dispatching performance suffered).See these other related answers of mine for more info:
jQuery .live() vs .on() method for adding a click event after loading dynamic html
How does jQuery's new on() method compare to the live() method in performance?
Should all jquery events be bound to $(document)?