Home >Web Front-end >JS Tutorial >Why Doesn't My jQuery on() Event Handler Work on Dynamically Added Elements?
Finding a Fix for jQuery's on() Event Handler
In jQuery, the transition from live() to on() for event handling has been a topic of discussion. Users have encountered issues where the on() event handler does not trigger. To address this, let's delve into the problem and identify the solution.
The documentation for on() clearly states that event handlers are bound only to elements that exist on the page when the code is executed. This starkly contrasts with the behavior of live(), which attached event handlers to elements dynamically added to the page.
To achieve similar functionality to live(), one needs to use the following pattern:
$(document.body).on('change', 'select[name^="income_type_"]', function() { alert($(this).val()); });
This approach binds the event handler not only to existing elements but also to elements that will be added in the future. It's imperative to bind the event handler as close to the target elements as possible for optimal performance.
In summary, when transitioning from live() to on(), it's crucial to bind event handlers dynamically added elements, such as those in dropdown lists. This ensures that the code works as expected and responds to user interactions effectively.
The above is the detailed content of Why Doesn't My jQuery on() Event Handler Work on Dynamically Added Elements?. For more information, please follow other related articles on the PHP Chinese website!