标签导航:

添加行(克隆)

本文介绍一种简单方法,实现表格行(tr)的动态克隆和删除,并确保始终保留至少一行。

需求:

  1. 添加行的按钮选择器:.addTr
  2. 删除行的按钮选择器:.removeTr

HTML 结构:

<table class="table table-hover">
  <thead>
    <tr>
      <th>product</th>
      <th>description</th>
      <th>action</th>
    </tr>
  </thead>
  <tbody class="productServicesTbody">
    <tr>
      <td></td>
      <td></td>
      <td><button class="addTr">add</button> <button class="removeTr">delete</button></td>
    </tr>
  </tbody>
</table>

JavaScript 代码 (jQuery):

$(document).ready(function() {
  $(document).on('click', '.addTr', function() {
    let $clone = $(this).closest('tr').clone();
    $clone.find('input').val(''); // 清空克隆行中的输入框 (如有)
    $('.productServicesTbody').append($clone);
  });

  $(document).on('click', '.removeTr', function() {
    if ($('.productServicesTbody tr').length > 1) {
      $(this).closest('tr').remove();
    }
  });
});

代码通过 jQuery 事件委托,监听 .addTr 和 .removeTr 按钮的点击事件。点击 "add" 按钮时,克隆当前行并添加到表格末尾;点击 "delete" 按钮时,如果表格中存在多于一行,则删除当前行。 确保至少保留一行。

如有任何疑问,请在评论区提出。 祝您编码愉快! #js #jquery