简体   繁体   中英

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. 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/

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. rowID is unique in the proper script so I can refer to the textareas of each row by '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:

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. I'd guess the answer involves live(); somehow but I'm not exactly sure where or how.

To make use of event delegation with on() (which replaces 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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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