在循环错误中将行添加到表中

Add row to table inside a loop error

本文关键字:添加 循环 错误      更新时间:2023-09-26

我在循环中有一个表,我想通过单击"添加行"按钮向表中添加一行。这是我的代码

HTML:

<div id="popUp" style="display: none">
    <input type="button" value="Cancel" onclick="closePopup()">
    <input type="button" value="ADD" onclick="addRow(this)"/>
</div>
@for (int i = 0; i < 3; i++) { 
    <table id="table @i" class="tableSum">
        <thead>
            <tr>
                <td>Items</td> 
                <td>Quantity</td>
                <td>Price</td>
            </tr>
        </thead>
        <tbody>
           <tr>
               <td>Apple</td>
               <td>5</td>
               <td>100</td>
           </tr>
            <tr>
               <td>Organe</td>
               <td>5</td>
               <td>200</td>
           </tr>
        </tbody>
        <tfoot>
            <tr>
               <td>Total</td>
               <td></td>
               <td></td>
           </tr>
             <tr><td colspan="3"><input type="button" class="addRow" onclick="addRow(this)" value="ADD ROW"/></td></tr>
        </tfoot>
    </table>
} 

然后在javascript中,我编写了函数:

function addRow(table) {
    $(table).find('tbody tr:last').clone().appendTo(table);
}

但是它没有添加一行。如果我使用不带参数"table"的函数,新行将添加到循环中的所有表中
我想要的结果是:当用户单击按钮时,只会在一个表中添加一个新行,而不是添加到所有表中。

td上的onclick="addRow(this)"。则CCD_ 3将表示所述替代CCD_。不是table。您可以传递id或表的某个选择器,或者在脚本中找到父table

您可以使用parents()来查找父table

function addRow(td) {
    var table = $(td).parents('table');
    var cloned = table.find('tbody tr:last').clone();
    table.find('tbody').append(cloned);
}

此外,如果您希望所有事件都能正常工作,请使用clone(true)。否则,您必须将事件bind转换为tr

您需要使用最接近的方法首先找到其父表:

function addRow(table) {
    $(table).closest('table')//find parent table
      .find('tbody tr:last')//find last tr of the table
      .clone()//clone it
      .appendTo($(table).closest('table').find('tbody'));//append it to tbody
  //append to 'tbody' not this row
}

根据您更新的问题,给您:

function addRow(table) {
    $(table).parent()//find parent div
      .next()//get the table
      .find('tbody tr:last')//find last tr of the table
      .clone()//clone it
      .appendTo($(table).parent().next().find('tbody'));//append it to tbody
  //append to 'tbody' not this row
}