将jQuery click事件添加到动态添加的内容 [英] adding jQuery click events to dynamically added content

查看:75
本文介绍了将jQuery click事件添加到动态添加的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中包含由php和mySQL填充的多行和多列.对于某些td,我将在document.ready函数中添加jQuery click-events,以使用户可以更改内容.

I have a table with multiple rows and columns populated by php and mySQL. For some of the td's I'm adding jQuery click-events in the document.ready function to let the user change the content.

但是我还有一个选择,可以向表中添加行并手动填充行.但是由于我要添加的行尚未在文档中准备好,因此它们不会附加click事件处理程序,因此我无法单击它们来获取输入框.

But I also have an option for adding rows to the table and populating them manually. But since the rows I'm adding aren't there on the document ready, they won't get the click event handler appended, and so I'm not able to click them to get input boxes.

<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>')
}

推荐答案

您要使用实时事件,在1.3中引入.

You want to use live events, which were introduced in 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()可能是一个更好的选择.请参阅下面的评论.

UPDATE: Note that as of jQuery 1.7, live() is deprecated. Use on() instead. And in some cases, delegate() may be a better choice. See the comments below.

关于如何使用 .on() 的示例:

Example of how to use .on():

$("table").on("click", "tr.clickable", function() {
   //add input fields
});

这篇关于将jQuery click事件添加到动态添加的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆