jQuery click事件不适用于动态字段 [英] jquery click event not working for dynamic fields
问题描述
Possible Duplicate:
jQuery - Click event doesn’t work on dynamically generated elements
我只有一个可单击的添加按钮,用于添加新表行.表格行中包含一个删除按钮.我注意到,当我动态添加新行时,该按钮不会触发click事件,但是如果该按钮在页面加载时存在,则可以正常工作.我该如何纠正?
I just have a clickable add button that adds new table rows. The table rows include a delete button. I've noticed that when I dynamically add a new row the button does not fire the click event, but if the button exists when the page loads, then it works fine. How can I correct this?
JavaScript:
Javascript:
$('#btnAdd').click(function () {
var newTr = '<tr><td><input id="column_0" name="column[0]" style="width:40%;" type="text" /> <img alt="Delete-icon24x24" class="btnDel clickable" id="" src="/assets/delete-icon24x24.png" /></td></tr>';
$('#columns').append(newTr);
});
$('.btnDel').click(function () {
alert('hey');
console.log('test');
var row = $(this).closest("tr");
alert(row);
row.remove();
});
推荐答案
您将需要使用事件委托:
You'll need to use event-delegation:
$("table").on("click", ".btnDel", function () {
/* Respond to click here */
});
原因是您无法将处理程序绑定到DOM中当前不存在的项目.但是,您可以将处理程序绑定到委托目标(将保留在DOM中的父元素).点击将使DOM冒泡,最终达到委托目标.
The reason is that you cannot bind a handler to items that don't presently exist in the DOM. You can, however, bind a handler to a delegate target (a parent element that will remain in the DOM). Clicks will bubble up the DOM, eventually reaching the delegate target.
我们监听table
上的点击,并评估它们是否来自.btnDel
元素.现在,这将响应页面加载时加载的.btnDel
元素的点击以及以后动态添加的点击.
We listen for clicks on the table
and we evaluate whether they came from an .btnDel
element. This will now respond to clicks from .btnDel
elements loaded when the page loaded, as well as those that are added dynamically later.
最后,不要重复使用ID值.
Lastly, don't re-use ID values.
这篇关于jQuery click事件不适用于动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!