简体   繁体   English

如何使用jQuery访问动态创建的页面元素

[英]How To Access Dynamically Created Page Elements with jQuery

I have a web app which uses jQuery to append rows onto the end of a table. 我有一个使用jQuery将行追加到表末尾的Web应用程序。 Each row has a textarea to make notes, and an edit button which pops up a window so more information can be entered. 每行都有一个做笔记的文本区域,以及一个弹出窗口的编辑按钮,因此可以输入更多信息。 The code to do so looks something like this: http://jsfiddle.net/H3m4z/ 这样做的代码如下所示: http : //jsfiddle.net/H3m4z/

That is a trimmed down version of the actual code because the real code it involves an AJAX call to save data from each table row into a database when it is added. 这是实际代码的精简版本,因为它的实际代码涉及AJAX调用,以在添加表时将每个表行的数据保存到数据库中。 rowID is unique in the proper script so I can refer to the textareas of each row by 'notes[rowID]'. rowID在适当的脚本中是唯一的,因此我可以通过'notes [rowID]'引用每一行的文本区域。

This is what I do when users enter more info on the edit popup window. 当用户在编辑弹出窗口中输入更多信息时,我就是这样做的。 Any new notes entered are saved into the database but to make the web app feel more 'live' and responsive the new notes are copied across from the edit window to their corresponding notes field in the parent table like so: 输入的所有新注释都会保存到数据库中,但要使Web应用程序看起来更“生动”,并作出响应,新注释将从编辑窗口复制到父表中的相应注释字段,如下所示:

window.opener.$('#notes[' + rowID + ']').text(newnotes);

This works absolutely fine for rows which already existed when the parent page was loaded, like the first table row in my example. 对于加载父页面时已经存在的行,这绝对好用,例如我示例中的第一行。 However it does not work for table rows which were dynamically added by jQuery. 但是,它不适用于由jQuery动态添加的表行。 I'd guess the answer involves live(); 我猜答案是live(); somehow but I'm not exactly sure where or how. 以某种方式,但我不确定在哪里或如何。

To make use of event delegation with on() (which replaces live() ): 要通过on() (代替live() )使用事件委托:

$('#table').on('click', 'td button', function(e){

});

Or you could just wrap your html in a jQuery function and bind the events right away (simplified example): 或者,您可以将html包装在jQuery函数中,然后立即绑定事件(简化示例):

var $tr = $('<tr><td>foo</td></tr>').on('click', function(e){

});

$tr.appendTo('#table');

This would obviously bind the event to the actual <tr> , but you get the idea. 显然,这会将事件绑定到实际的<tr> ,但是您明白了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM