动态创建的元素上的事件处理程序? [英] Event handlers on dynamically created elements?
问题描述
$(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>
嗨!我的"$('.alert-button').on('click'...")代码适用于在页面加载时创建的元素,但不适用于动态创建的元素.
Hi! My " $('.alert-button').on('click'..." code works on elements created on page load, but not on dinamically created ones.
所以我有一个带有2个按钮的页面(请运行上面的代码段).如果单击单击我!"提醒嗨!"出现.
So i have a page with 2 buttons (please run the snippet above). If you click on "Click me!" alert "Hi!" appears.
但是当我重复点击我!"通过点击添加按钮"按钮,在重复的点击我!"上单击不会发出警报嗨!" (尽管它也具有".alert-button"类).
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.
我在做什么错了?:)
推荐答案
只需替换此函数:
$(document).on('click','.alert-button', function () {
alert('HI!');
});
这还将绑定click事件到动态添加的元素上.
This will also bind the click event on dynamically added element.
这篇关于动态创建的元素上的事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!