问题
$(document).ready(function () {
$('.add-button').on('click', function () {
$('.alert-button').after('<button type="button" class="alert-button">Click me! </button><br>');
});
$('.alert-button').on('click', function () {
alert('HI!');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button' class="alert-button">Click me! </button><br>
<button type="button" class="add-button">Add button!</button>
Hi! My " $('.alert-button').on('click'..." code works on elements created on page load, but not on dinamically created ones.
So i have a page with 2 buttons (please run the snippet above). If you click on "Click me!" alert "Hi!" appears.
But when I duplicate "Click me!" button via pressing "Add button", a click on the duplicated "Click me!" produces no alert "Hi!" (although it also has ".alert-button" class).
I want to see alert "Hi!" when I click on any "Click me!" button.
what am I doin' wrong?:)
回答1:
Just replace this function :
$(document).on('click','.alert-button', function () {
alert('HI!');
});
This will also bind the click event on dynamically added element.
回答2:
The click handler is only bound to elements that already exist. You'll need to add handlers to elements as they're dynamically created. In your case, the best place to do that is in the .on
function right after the new element is created.
来源:https://stackoverflow.com/questions/44552107/event-handlers-on-dynamically-created-elements