添加&从克隆的表行中删除细胞

时间:2018-05-23 01:59:43

标签: javascript jquery html html-table

我正在尝试创建一个我可以添加的表格&根据需要删除行。表本身是使用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++;
}

3 个答案:

答案 0 :(得分:1)

您应该尝试使用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>

答案 1 :(得分:0)

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

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

它的工作方式是在DOM树上找到与被点击的元素最接近的tr元素(这是特定的group_remove类元素)。然后,该元素及其中的所有内容都将被删除。

答案 2 :(得分:0)

<?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);
}
相关问题