仅删除 tbody 上的 tr

Posted

技术标签:

【中文标题】仅删除 tbody 上的 tr【英文标题】:Remove only the tr on the tbody 【发布时间】:2016-01-30 12:15:38 【问题描述】:

我有一个 html,其中当然有一个 table 元素,并且在 tbody 中,我有一个用于删除表格行的按钮。

我已经为按钮分配了onclick="" 函数。 (Function here)

如何只删除表体 (tbody) 中的行,而不删除表头 (thead) 中的行?

FIDDLE HERE

【问题讨论】:

请贴出代码 What is the best way to remove a table row with jQuery?的可能重复 【参考方案1】:

将正文行包装到 tbody 元素,然后您可以仅选择要删除的 table tbody tr。使用 jQuery 你可以做到$('table tbody tr').remove();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Some content</td>
      <td>
        <button onClick="$(this).closest('tr').remove()">Remove</button>
      </td>
    </tr>

    <tr>
      <td>Some content</td>
      <td>
        <button onClick="$(this).closest('tr').remove()">Remove</button>
      </td>
    </tr>

    <tr>
      <td>Some content</td>
      <td>
        <button onClick="$(this).closest('tr').remove()">Remove</button>
      </td>
    </tr>

    <tr>
      <td>Some content</td>
      <td>
        <button onClick="$(this).closest('tr').remove()">Remove</button>
      </td>
    </tr>
  </tbody>
</table>
<button onClick="$('#table tbody tr').remove()">Remove all rows</button>

【讨论】:

以上是关于仅删除 tbody 上的 tr的主要内容,如果未能解决你的问题,请参考以下文章

从自定义表格槽中删除了 THEAD、TBODY、TR HTML 元素

jQuery:如何删除表中的 tr 标签?

jquery 删除table行,该如何解决

表格事件,表格删除行

js如何实现点击新增按钮之后自动增加一行,最多增加四行

jQuery:点击按钮删除最近的内容需要什么