开发者

Best way to add tr element mid-way through a list of table rows - jQuery

first post on the site!

I'm looking for some help inserting tr elements mid-way through a simple table like the one below:

<table id="content">  
<tr class="item">  
<td><p>header content</p></td>  
</tr>  
<tr class="item">  
<td><p>footer content</p></td>  
</tr>  
</table>

I am adding elements using jQuery with the following code:

$('<tr class="item" />').insertAfter('#content tr:first');

However after adding an element using this command, I would like to add some more (but after the last added item, not at the top of the list)

Im sure there are simple ways of开发者_如何学运维 doing this (by assigning an id to the footer element, and using .insertBefore('#footer') for example) but it would be interesting to know some different techniques that could be used. Thanks in advance! :)


If the row will always be assigned to the element before the footer row, then your idea to add an ID would seem to make sense.

If you don't want to use an ID, then use an idea similar to your :first selector. Do insertBefore('#content tr:last');

$('<tr class="item" />').insertBefore('#content tr:last');


The :eq selector should be handy in your case:

// insert after first row
$('<tr class="item" />').insertAfter('#content tr:eq(0)');
// insert after second row
$('<tr class="item" />').insertAfter('#content tr:eq(1)');
// insert after third row
$('<tr class="item" />').insertAfter('#content tr:eq(2)');
// and so on


From a possibility standpoint, you could do this, but best practices would show that it'd be better to build all of your html first, and then inject it.

So, something like this would be best

$('#content tr:first').after(function(){
  var html = "";
  for(var i = 0; i < NUM_OF_ROWS; i++) {
    html += '<tr class="item" />';
  }
  return html;
});

That way there is only one access to the dom and it's all pretty and up in one function.

(this does require 1.4.x though)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜