javascript - 删除表中除标题行外的所有行

标签 javascript jquery

使用Javascript(与JQuery),我想删除表中除标题行之外的所有行。
这似乎很简单,因为我在StackOverFlow上看到了很多与此相关的帖子,以及许多提供和接受的解决方案。但是,它们似乎都不适合我。请引用下面的代码:

function delTable() {
  console.log("Delete all rows, but the header");

  // Option-A
  // $('#TableA tbody tr').remove();

  // Option-B
  // Accepted answer for: https://stackoverflow.com/questions/9420203/how-to-remove-all-rows-of-the-table-but-keep-the-header
  // $('#TableA tr').not(function(){ return !!$(this).has('th').length; }).remove();

  // Option-C
  $('#TableA tbody').empty();

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<body onLoad="delTable();">
  <table id="TableA">
    <th>
      <tr>
        <td>Col A</td>
        <td>Col B</td>
      </tr>
    </th>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
      <tr>
        <td>3</td>
        <td>4</td>
      </tr>
    </tbody>
  </table>

</body>

</html>

有人知道我在做什么错吗?谢谢。
-卡尔提克

最佳答案

只需将您的th更新为thead,然后您就可以开始使用了,见下文:
HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>

  
</head>
<body onLoad="delTable()">
  <table id="TableA">
    <thead>
      <tr>
        <td>Col A</td>
        <td>Col B</td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
      <tr>
        <td>3</td>
        <td>4</td>
      </tr>
    </tbody>
  </table>

</body>
</html>
JS:
function delTable() {
  console.log("Delete all rows, but the header");

  // Option-A
  // $('#TableA tbody tr').remove();

  // Option-B
  // Accepted answer for: https://stackoverflow.com/questions/9420203/how-to-remove-all-rows-of-the-table-but-keep-the-header
  // $('#TableA tr').not(function(){ return !!$(this).has('th').length; }).remove();

  // Option-C
  $('#TableA tbody').empty();

}
工作提琴:
https://jsfiddle.net/pvfkxdby/1/

关于javascript - 删除表中除标题行外的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62764334/

相关文章:

javascript - 让用户通过 javascript 访问 cookie 是一个安全问题吗

JavaScript Object.create 现有对象的样式

jquery - 单击多个按钮之一,在文本输入中输入值

php - 如何通过 PHP 和 Javascript 了解客户端操作系统?

javascript - 在函数中解构数组失败并显示 "let is not defined"?

javascript - Polymer 1.0 Local Dom 与 this.$ 选择器相关的问题

jquery - 创建模糊的背景效果

jquery - 查找具有特定值的自定义属性的元素并替换它

javascript - 下拉列表中有很多项目,我可以与多个下拉列表共享此列表吗?

javascript - 如何在另一个开始之前定位并结束一个 jquery 事件?