我有一张桌子
<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>');
现在,当我单击Cell 3或Cell 4时,不会触发alert
消息。
如何在不刷新页面的情况下解决这个问题?
答案 0 :(得分:1)
用户jquery "on"
方法而不是bind。
https://api.jquery.com/on/
它与绑定的主要区别在于它对选择器中的元素执行一种监视并添加“实时绑定”。
这是样本:
http://jsbin.com/yapiheju/1/edit
答案 1 :(得分:0)
您还必须将事件侦听器重新分配给新的DOM节点。 在dinamically添加一个单元格之后,请确保在其上设置一个监听器。
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().
或者您可以像其他用户建议的那样使用委托事件和jQuery的on
。您所要做的就是找出哪个元素比DOM中的核心文档更接近核心文档,当您附加事件时,它肯定会作为真实节点出现。在您的情况下,最好选择document
本身,因为您不需要等待整个DOM加载。
现在,只需将点击事件设置为document
即可。因此,每次点击事件都会到达document
(通过直接点击或冒泡到它),将触发回调。但我们不希望如此。嗯,这很简单。只需在事件名称和回调之间再向.on()
方法传递一个参数。该参数将是一个指向后代的选择器字符串,允许将此特定事件冒泡到document
。
答案 2 :(得分:0)
使用jquery on
例如。
$(document).on("click",
"#table1 tr td", function(){
alert('Selected');
});