首页 > 解决方案 > .insertRow() 为空时无法正常工作

问题描述

当我尝试插入一行以清空<tbody>我的表时,它添加的行<thead>不是空的,但不是<tbody>.

例子:

<!DOCTYPE html>
<html>
<body>
  <table id="myTable">
    <thead style="background-color: red;">
      <tr>
        <td>A</td>
        <td>B</td>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
  <br>
  <button type="button" onclick="myFunction()">Try it</button>
  <script>
    function myFunction() {
      var table = document.getElementById("myTable");
      var row = table.insertRow();
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      cell1.innerHTML = "NEW CELL1";
      cell2.innerHTML = "NEW CELL2";
    }
  </script>
</body>
</html>

编辑

解决方案:<tbody><tr></tr></tbody>,但不是很清楚...

标签: javascripthtmldom

解决方案


一个表包含三个部分:theadtbodytfoot。您的代码没有理由根据需要向 tbody 插入新行。如果您想在 tbody 中添加一行,则需要提及它。在你的男女同校做一点改变:

function myFunction() {
  var table = document.getElementById("myTable").getElementsByTagName('tbody')[0];
  var row = table.insertRow();
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = "NEW CELL1";
  cell2.innerHTML = "NEW CELL2";
}

推荐阅读