2012-08-10 48 views
0

我一直在尋找各種各樣的StackOverflow和Google的答案,我一直無法弄清楚這一點。使用jQuery將行添加到頁面上的特定表格

我想要做的是在我的頁面上添加一行到許多表格之一。現在,所有「添加行」請求都會添加到第一個表中。

這裏是我的javascript:

$(document).ready(function() { 
$("a#add_row").click(function() { 
$('#ListTable1').height($('#collapse1').height() + 60) 
    $("#delTable").find('tbody') 
    .append($('<tr>') 
     .append($('<td>') 
      .append('<input type="text" name="name[]" size="5"class="input input-small" />')) 
       .append($('</td>') 
       ) 
       .append($('<td>') 
       .append('<input type="text" name="endpoint[]" size="5" class="input input-small" />')) 
       .append($('</td>') 
       ) 
       .append($('<td style="width: 20px">') 
       .append() 
       .append($('</td>') 
       )) 
      .append($('</tr>')) 
     ); 
    }); 
}); 

這裏是我開始的每個表:

<table class="table" id="listTable1" style="width: 280px;"> 
<thead>...the head...</thead> 
<tbody>...all sorts of rows. Added row goes at the end of the tbody...</tbody> 
<tfoot> 
    <tr> 
     <td><a id="add_row">Add Row</a></td><td></td> 
    </tr> 
</tfoot> 
</table> 

,這裏是按鈕我使用:

<a id="add_row">Add Row</a> 

我知道我必須爲每個表的ID增加id,但我不知道如何處理Javascript向執行請求的表添加一行。

我該如何得到這個工作?

+0

@大衛:儘量不要使用追加多,它不僅是大量的方法調用,但每個'$()'問jQuery的產生一個新的對象。很多性能處罰在那裏進行。做類似的事情:'var tableRow ='​​​​'; $(「#delTable」)。find('tbody')。append(tableRow);' – Nope 2012-08-10 23:43:28

回答

1

您可以使用closest來獲得相關表格:

$("#add_row").click(function() { 
    var $theTable = $(this).closest("table"); 

    // do your thing 
}); 

正如你提到的,每個按鈕的id shoudl是唯一的。我會建議使用一個班級,使您的選擇.add_row

+0

很酷!我不知道.closest()我會建議.parents(「表」) – Robodude 2012-08-10 23:34:44

+0

@Robodude是的,父母會工作,除非有嵌套表,它會將它們全部返回。最接近的很好,因爲它只返回匹配選擇器的最近的祖先。 – 2012-08-10 23:35:45

+0

保存了一天,非常感謝 – David 2012-08-10 23:49:01

1

將表格和按鈕放在div中,然後使用parent();

的Javascript

$(document).ready(function() { 

    $("a#add_row").click(function() { 

    var table = $(this).parent().find('table'); 


    table.height($('#collapse1').height() + 60) 

    $("#delTable").find('tbody').append($('<tr>') 
    .append($('<td>') 
    .append('<input type="text" name="name[]" size="5"class="input input-small" />')) 
      .append($('</td>') 
      ) 
      .append($('<td>') 
      .append('<input type="text" name="endpoint[]" size="5" class="input input-small" />')) 
      .append($('</td>') 
      ) 
      .append($('<td style="width: 20px">') 
      .append() 
      .append($('</td>') 
      )) 
     .append($('</tr>')) 
    ); 
}); 
}); 

HTML

<div id="container"> 

    <table class="table" id="listTable1" style="width: 280px;">...</table> 
    <a id="add_row">Add Row</a> 

</div> 
相關問題