我有一个包含多行和多列的表,由 php 和 mySQL 填充。对于某些 td,我在 document.ready 函数中添加 jQuery 单击事件,以便用户更改内容。
但我还可以选择向表中添加行并手动填充它们。但由于我要添加的行尚未在文档中准备好,因此它们不会附加单击事件处理程序,因此我无法单击它们来获取输入框。
<table>
<tr>
<td class="clickable">Some info</td>
<td class="clickable">Some more info</td>
<td>Unchangable info</td>
</tr>
... more similar rows ...
</table>
然后是 jQuery
$("tr.clickable").click(function() {
//add input fields
}
$("span#addNewRow").click(function() {
$("table").append('<tr><td class="clickable"></td> ... </tr>')
}
最佳答案
您想使用live events ,在 1.3 中引入。
$("tr.clickable").live("click", function() {
//add input fields
});
$("span#addNewRow").live("click", function() {
$("table").append('<tr><td class="clickable"></td> ... </tr>')
});
更新:请注意,从 jQuery 1.7 开始,live()
已被弃用。使用 on()
代替。在某些情况下,delegate()
可能是更好的选择。请参阅下面的评论。
如何使用.on()
的示例:
$("table").on("click", "tr.clickable", function() {
//add input fields
});
关于jquery - 添加 jQuery 点击事件来动态添加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/852450/