Home > Web Front-end > JS Tutorial > How Can I Handle Events from Dynamically Added Elements in jQuery?

How Can I Handle Events from Dynamically Added Elements in jQuery?

Patricia Arquette
Release: 2024-12-11 19:50:19
Original
651 people have browsed it

How Can I Handle Events from Dynamically Added Elements in jQuery?

Handling Events Triggered by Dynamically Generated Elements

When dynamically adding elements to the DOM, capturing events triggered by those elements using standard event handlers can be problematic. This issue arises because the event handlers are attached before the elements are created, resulting in the events not being captured.

jQuery provides a solution to this issue through the use of the .on() method (or .delegate() in older versions). This method allows you to delegate the event handling to a static ancestor element, which already exists when the handler is bound. This ensures that events bubble up and can be captured by the handler.

In your specific case, you can modify your code to use the .on() method as follows:

// jQuery 1.7 or above
$('#modal').on('keyup', 'input', function() {
    handler = $(this).val();
    name = $(this).attr('name');
});
Copy after login

// jQuery 1.6 or below

$('#modal').delegate('input', 'keyup', function()
{
    handler = $(this).val();
    name = $(this).attr('name');
});
Copy after login

By delegating the event handling to the #modal element, which already exists when the event handlers are bound, you can capture events triggered by dynamically generated input elements within that element.

The above is the detailed content of How Can I Handle Events from Dynamically Added Elements in jQuery?. 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