jQuery: add row to table and the select it in DOM
I want to add a row to a table, and then use it as a DOM object. Suppose the following HTML:
<table>
<tr class="existing-row"><td>
<a>add new row</a>
</td></tr>
<tr class="existing-row"><td>
<a>add new row</a>
</td></tr>
</table>
I use the following JavaScript with jQuery to insert a row:
function addNewRow(addNewRowLink)
{
var currentRow = addNewRowLink.closest('tr');
currentRow.after('<tr class="added-row"><td>This is new</td></tr>');
var newRowInDomTree = currentRow.next('tr');
//This does not work
}
The variable newRowInDomTree
contains a tr.existing-row
instead a tr.added-row
. It seems that th开发者_运维知识库e DOM tree is not updated, but I don't undertand why.
Any ideas?
Your code should work, except that I can't see how it is being called, so I don't know what addNewRowLink
actually is.
An alternative would be to retain a reference to the new element when creating it. Like this:
function addNewRow(addNewRowLink) {
var currentRow = addNewRowLink.closest('tr');
var newRowInDomTree = $('<tr class="added-row"><td>This is new</td></tr>')
.insertAfter( currentRow );
// newRowInDomTree will be the element you created
}
I think the effect you're looking for can be simplified by using the right function:
instead of:
currentRow.after('<tr class="added-row"><td>This is new</td></tr>');
you should try:
newRowInDomTree = $('<tr class="added-row"><td>This is new</td></tr>').insertAfter(currentRow);
I'd venture a guess that your selection (currentRow.next('tr')
) is happening before the element is actually added to the dom. You could try listening for an onload
or onreadystatechange
event to see if it's being fired later.
How about you just do it like this?
$(".existing-row a").click(function() {
newRow = $(this).parent.after('<tr class="added-row"><td>This is new</td><tr>');
});
Give an id to the table. ie,
< table id="me">
var iHtml = ' < tr class="added-row">< td>This is new asdasdasd< /td>< /tr>' ;
$('#me tr:last').after('iHtml ');
精彩评论