我有这样的脚本:
$(document).ready(function() {
$('.button').click(function() {
var button = document.createElement('button');
$(button).addClass('button');
$(button).html('Button');
$(button).appendTo('.container');
});
});
示例:jsfiddle
按钮是由按钮单击尚未单击事件创建的。如何附加此事件以使用任何按钮创建按钮?
最佳答案
您需要delegate the event handler使用动态生成的元素。
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
您可以使用 on()
委托(delegate)处理程序的方法如下:
$(document).on("click",".button",function() {})
关于javascript - 如何将点击事件绑定(bind)到点击事件时创建的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25807342/