繁体   English   中英

从克隆表行中添加和删除单元格

[英]Add & Remove Cells from Cloned Table Rows

我正在尝试创建一个表,我可以根据需要添加和删除行。 表格本身是使用 PHP 即时创建的,我无法知道每个表格行中有多少个单元格。 到目前为止,我已经能够成功添加行,但是在按下“X”时如何删除特定行一直受阻。

我想,如果我可以将一个数字传递给“删除”函数,它可以用来确定要删除的行。 我一直在尝试从克隆数据中删除最终的“td”,并将其替换为包含正确函数参数的“td”。

到目前为止,我尝试过的一切都没有奏效。 有什么建议?

HTML

<table class='group'>
  <tr class='group_row_0'>
    <td>Thing 1</td>
    <td>Thing 2</td>
    <td>Thing 3</td>
    <td>Thing 4</td>
    <td>
      <a href='#' class='group_remove' onclick='javascript:removeGroupField(0);'>X</a> <!-- The "0" here needs to be replaced with the new row # -->
    </td>
  </tr>
</table>

<a href='#' class='group_add' onclick='javascript:addGroupField();'>+ Add Row</a>

Javascript:

var row_index = 1;

function addGroupField(){
  var last_row = row_index-1;

  var rowData = $('.group_row_'+last_row).clone();
  rowData.attr('class','group_row_'+row_index);

  $('.group').append(rowData);

  row_index++;
}

您应该尝试使用 Javascript 正确附加处理程序,而不是使用内联处理程序。 只需向表中添加一个处理程序,当单击X时,通过从单击的按钮向上导航到要删除的tr来删除行:

 $('table.group').on('click', '.group_remove', function() { const tr = this.parentElement.parentElement; tr.remove(); }); $('.add').on('click', function (){ const cloned = $('.group tr:last-child').clone(); $('.group').append(cloned); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class='group'> <tr class='group_row_0'> <td>Thing 1</td> <td>Thing 2</td> <td>Thing 3</td> <td>Thing 4</td> <td> <a href='#' class='group_remove'>X</a> </td> </tr> <tr class='group_row_1'> <td>Thing 1</td> <td>Thing 2</td> <td>Thing 3</td> <td>Thing 4</td> <td> <a href='#' class='group_remove'>X</a> </td> </tr> <tr class='group_row_2'> <td>Thing 1</td> <td>Thing 2</td> <td>Thing 3</td> <td>Thing 4</td> <td> <a href='#' class='group_remove'>X</a> </td> </tr> <tr class='group_row_3'> <td>Thing 1</td> <td>Thing 2</td> <td>Thing 3</td> <td>Thing 4</td> <td> <a href='#' class='group_remove'>X</a> </td> </tr> </table> <div class="add">add row</div>

看起来你正在使用一些 jQuery,所以你可以为 x 尝试这个。

$(document).on('click', '.group_remove', function(){
    $(this).closest('tr').remove();
});

它的工作原理是向上 DOM 树查找与被单击元素最近的 tr 元素(这是特定的 group_remove 类元素)。 然后,该元素以及其中的所有内容都将被删除。

<?php
      echo "<table border=0 width=100%>
               <tr id='tabRow'></tr>
            </table>";
      echo "<center><button = addcell();>Add</button></center>";
 ?>

脚本

function addcell() 
{
   var row           = document.getElementById("tabRow");
   var nrow          = row.cells.length;    
   var addcell       = row.insertCell(nrow);
   addcell.align     = "right";
   addcell.innerHTML = "<font color=red onclick=deletecell(this)><sup>X</sup></font>Hello World";
}

function deletecell(rmvcell)
{
   document.getElementById("tabRow").deleteCell(rmvcell.cellIndex);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM