jQuery's live() method faced deprecation in version 1.7, necessitating a switch to on(). While replacing live() with on() should ideally yield similar results, the on() documentation emphasizes that event handlers only bind to currently selected elements present on the page at the time of binding.
Original Implementation (live()):
$('select[name^="income_type_"]').live('change', function() { alert($(this).val()); });
Replacement (on()):
$('select[name^="income_type_"]').on('change', function() { alert($(this).val()); });
The discrepancy with live() stem from the fact that on() only binds to currently existing elements, unlike live()'s delegation mechanism that attached event handlers to elements dynamically added to the DOM.
Correct Use of on() for Dynamic Elements:
To maintain event handling for dynamically added elements with on(), the event handler must be bound to a parent element that exists on the page at the time of binding. This can be achieved by using:
$(document.body).on('change', 'select[name^="income_type_"]', function() { alert($(this).val()); });
Alternatively, event delegation can be applied closer in the element hierarchy to improve specificity.
jQuery Documentation Hinweis:
The live() documentation explicitly notes that rewriting live() in terms of its successors involves binding event handlers to existing elements:
$(document).on(events, selector, data, handler); // jQuery 1.7+
The above is the detailed content of How to Correctly Migrate jQuery's `live()` to `on()` for Dynamically Added Elements?. For more information, please follow other related articles on the PHP Chinese website!