Home > Web Front-end > JS Tutorial > How to Attach Event Handlers to Dynamically Added Elements with jQuery?

How to Attach Event Handlers to Dynamically Added Elements with jQuery?

Patricia Arquette
Release: 2025-01-05 11:10:43
Original
188 people have browsed it

How to Attach Event Handlers to Dynamically Added Elements with jQuery?

How to Bind Events to Dynamic Elements Using jQuery

Suppose you have existing jQuery code that attaches event handlers to elements with the class .myclass. However, in scenarios where these elements are dynamically added to the page via AJAX or DHTML, the newly created elements won't have the click handler associated with them.

Problem Solution

To handle this issue, jQuery offers several approaches:

1. .on() Method (jQuery 1.7 ):

Replace the .live() method with .on() and specify a selector that combines the parent element with .myclass as an argument.

$('body').on('click', 'a.myclass', function() {
    // do something
});
Copy after login

This will attach the click handler to all tags with the .myclass class, regardless of when they are added to the page.

2. .delegate() Method (jQuery 1.6 - 1.8):

The .delegate() method acts similarly to .on() but requires the parent element to be specified in brackets:

$('body').delegate('a.myclass', 'click', function() {
    // do something
});
Copy after login

Both .on() and .delegate() allow for event handling on dynamically added elements.

The above is the detailed content of How to Attach Event Handlers to Dynamically Added Elements with 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