2012-09-15 4 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 : JQuery와 함께

<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> 

:

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