删除表中除标题行之外的所有行

Kar*_*hik 5 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();

}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

有谁知道我做错了什么?谢谢。

-卡蒂克

小智 1

只需将您的 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>
Run Code Online (Sandbox Code Playgroud)

JS:

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

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

  // Option-B
  // Accepted answer for: /sf/ask/659414241/
  // $('#TableA tr').not(function(){ return !!$(this).has('th').length; }).remove();

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

}
Run Code Online (Sandbox Code Playgroud)

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