[英]jQuery selector not firing after dynamically adding a row to a table
我有一张桌子
<table id="table1">
<tr>
<td>Cell 1</td>
<td>Cell2</td>
</tr>
</table>
在选择单元格时
$('#table1 tr td').bind('click', function(){
alert('Selected');
})
但是,当我动态添加单元格时
$(this.parentNode).after('<tr><td>Cell 3</td><td>Cell 4</td></tr>');
现在,当我单击单元格3或单元格4时,不会触发alert
消息。
如何在不刷新页面的情况下解决此问题?
用户jquery的"on"
方法代替绑定。 https://api.jquery.com/on/与bind的主要区别是它对选择器中的元素执行某种监视并添加“实时绑定”。 这是示例: http : //jsbin.com/yapiheju/1/edit
您还必须将事件侦听器重新分配给新的DOM节点。 在动态添加一个单元格之后,请确保您也对其设置了一个侦听器。
jQuery docs: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
或者,您也可以按照其他用户的建议,将委托事件与jQuery的on
一起使用。 您要做的就是找出在DOM中比单元更接近核心文档的元素,并确保在附加事件时将其作为真实节点显示。 在您的情况下,最好选择document
本身,因为您无需等待整个DOM加载。
现在,只需将click事件设置为document
。 因此,每次单击事件到达document
(通过直接单击或冒泡到document
)时,都会触发回调。 但是我们不想要那样。 好吧,很简单。 只需在事件名称和回调之间传递一个参数给.on()
方法即可。 此参数将是一个选择器字符串,指向后代,该后代将允许将此特定事件冒泡到document
。
在on
使用jQuery
例如。
$(document).on("click",
"#table1 tr td", function(){
alert('Selected');
});
此处的文档: http : //api.jquery.com/on/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.