Home > Web Front-end > JS Tutorial > How to Correctly Migrate jQuery's `live()` to `on()` for Dynamically Added Elements?

How to Correctly Migrate jQuery's `live()` to `on()` for Dynamically Added Elements?

Linda Hamilton
Release: 2024-12-16 05:22:10
Original
729 people have browsed it

How to Correctly Migrate jQuery's `live()` to `on()` for Dynamically Added Elements?

Transitioning from live() to on() in jQuery: Debugging Event Binding

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());
});
Copy after login

Replacement (on()):

$('select[name^="income_type_"]').on('change', function() {
    alert($(this).val());
});
Copy after login

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());
});
Copy after login

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+
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template