2012-09-15 38 views
1
​<table id="table"> 
    <tr><td>one</td><td>two</td></tr> 

    <tr id="sum"><td>sum</td><td>sum2</td></tr> 
    </table> 

    ​<span id="add">add new</span>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

$('#add').click(function(){ 
    $('#table').append('<tr><td>one</td><td>two</td></tr>'); 
})​ 

我怎樣才能使這添加新元素作爲倒數第二個元素追加? 我希望#sum仍然是最後一個元素。表追加沒有最後一個元素

回答

7

使用insertBefore()

$('#add').click(function(){ 
    $('<tr><td>one</td><td>two</td></tr>').insertBefore('#sum'); 
})​ 

JS Fiddle demo

你也可以簡單地使用多個tbody元素,一個包含了#sum行,其他的,在這個例子中,#content

<table id="table"> 
    <tbody id="content"> 
     <tr><td>one</td><td>two</td></tr> 
    </tbody> 
    <tbody> 
     <tr id="sum"><td>sum</td><td>sum2</td></tr> 
    </tbody> 
</table> 

隨着jQuery的:

$('#add').click(function(){ 
    $('#content').append('<tr><td>one</td><td>two</td></tr>'); 
})​ 

JS Fiddle demo

,或者可能使用tfoot(雖然我不知道這一個適當的用例的tfoot元素:

<table id="table"> 
    <tfoot> 
     <tr id="sum"><td>sum</td><td>sum2</td></tr> 
    </tfoot> 
    <tbody id="content"> 
     <tr><td>one</td><td>two</td></tr> 
    </tbody> 
</table> 

和jQuery:

$('#add').click(function(){ 
    $('table tbody').append('<tr><td>one</td><td>two</td></tr>'); 
})​ 

JS Fiddle demo

參考文獻:

1

您可以使用.before()

$('#add').click(function(){ 
    $('#sum').before('<tr><td>one</td><td>two</td></tr>'); 
})​ 
1

真正簡單的:)使用before

$('#add').click(function(){ 
    $('#sum').before('<tr><td>one</td><td>two</td></tr>'); 
})​; 
1

只要做到:

$('#sum').before('<tr><td>one</td><td>two</td></tr>'); 
相關問題