2010-08-26 72 views
94

我知道如何添加或使用jQuery的前面加上一個新行插入表:jQuery的在一定的指數插入新行插入到表

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

如何我插入行(在html變量給出)成一個特定的「行索引」i。因此,例如,如果i=3,該行將作爲表中的第4行插入。

+0

不一樣,但與http://stackoverflow.com/questions/171027/add-table-row-in-jquery – 2012-07-18 15:32:23

回答

132

您可以使用.eq().after()這樣的:

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

的索引是從零開始的,所以是第4行,你需要i-1,因爲.eq(3)將是第4行,你需要回去到第3行(2)並插入.after()即可。

+7

應該注意的是,如果jQuery的eq函數被賦予一個負值,它將循環到表的末尾。因此,運行此操作並試圖將其插入到0索引將導致新行插入到末尾 – rossisdead 2011-12-22 14:23:10

+2

如果您希望在索引 – Abhi 2013-12-17 04:30:40

+1

之前插入'.before(html)',則會失敗,如果沒有表中的行,沒有人有一個解決方案(基於索引)哪些工作,即使是第一行? – MartinM 2014-04-29 13:20:46

-1
$($('#my_table > tbody:last')[index]).append(html); 
+4

相關這總是會導致索引超出範圍異常。 – 2010-08-26 17:47:44

14

試試這個:

var i = 3; 

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

或本:

var i = 3; 

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

或本:

var i = 4; 

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

所有這些都將放置在該行中的相同位置。 nth-child使用基於1的索引。

0

使用eq selector到SELCT第n行(從0開始),並添加行使用after後,所以:

$('#my_table > tbody:last tr:eq(2)').after(html); 

其中HTML是一種tr

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

試試這個:

$("table#myTable tr").last().after(data); 
2

說明:

$('#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 
0

我知道它的到來較晚,但誰想要實現它純粹使用JavaScript那些人,這裏是你如何能做到這一點:

  1. 獲取參考目前tr被點擊。
  2. 製作一個新的tr DOM元素。
  3. 將其添加到被稱爲tr的父節點。

HTML:

<table> 
    <tr> 
        <td> 
         <button id="0" onclick="addRow()">Expand</button> 
        </td> 
        <td>abc</td> 
        <td>abc</td> 
        <td>abc</td> 
        <td>abc</td> 
    </tr> 

    <tr> 
        <td> 
         <button id="1" onclick="addRow()">Expand</button> 
        </td> 
        <td>abc</td> 
        <td>abc</td> 
        <td>abc</td> 
        <td>abc</td> 
    </tr> 
    <tr> 
        <td> 
         <button id="2" onclick="addRow()">Expand</button> 
        </td> 
        <td>abc</td> 
        <td>abc</td> 
        <td>abc</td> 
        <td>abc</td> 
    </tr> 

在JavaScript:

function addRow() { 
     var evt = event.srcElement.id; 
     var btn_clicked = document.getElementById(evt); 
     var tr_referred = btn_clicked.parentNode.parentNode; 
     var td = document.createElement('td'); 
     td.innerHTML = 'abc'; 
     var tr = document.createElement('tr'); 
     tr.appendChild(td); 
     tr_referred.parentNode.insertBefore(tr, tr_referred.nextSibling); 
     return tr; 
    } 

這將增加正好在其上單擊按鈕行下面的新錶行。