Jquery insert new row into table at a certain index

I know how to append or prepend a new row into a table using jquery:

$('#my_table > tbody:last').append(html);

How to I insert the row (given in the html variable) into a specific "row index" i . So if i=3 , for instance, the row will be inserted as the 4th row in the table.


You can use .eq() and .after() like this:

$('#my_table > tbody > tr').eq(i-1).after(html);

The indexes are 0 based, so to be the 4th row, you need i-1 , since .eq(3) would be the 4th row, you need to go back to the 3rd row ( 2 ) and insert .after() that.


Try this:

var i = 3;

$('#my_table > tbody > tr:eq(' + i + ')').after(html);

or this:

var i = 3;

$('#my_table > tbody > tr').eq( i ).after(html);

or this:

var i = 4;

$('#my_table > tbody > tr:nth-child(' + i + ')').after(html);

All of these will place the row in the same position. nth-child uses a 1 based index.


注意:

$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody

$("table#myTable tr").last().after(newRow);  // this will add new row outside tbody 
                                             //i.e. between thead and tbody
                                             //.before() will also work similar
链接地址: http://www.djcxy.com/p/22974.html

上一篇: 如何使用jQuery将行添加到表中?

下一篇: Jquery在某个索引处插入新行到表中