Html表使用javascript动态添加和删除行

卡梅伦121341

我想要一个最初没有行的表,然后动态创建每一行并且能够删除每一行。我得到了无法读取未定义的属性“childNodes”请告诉我应该怎么做,谢谢。

function addRow() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = "NEW CELL1";
  cell2.innerHTML = "NEW CELL2";
}

function deleteRow(tableID) {
  try {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    for (var i = 0; i < rowCount; i++) {
      var row = table.rows[i];
      var chkbox = row.cells[0].childNodes[0];

      table.deleteRow(i);
      rowCount--;
      i--;
    }
  } catch (e) {
    alert(e);
  }
}
<!DOCTYPE html>
<html>

<head>
  <style>
    table,
    td {
      border: 1px solid black;
    }
  </style>
</head>

<body>

  <p>Click the button to add a new row at the first position of the table and then add cells and content.</p>

  <table id="myTable">
    <TR>

    </TR>
  </table>
  <br>

  <button type="button" onclick="addRow()">Add</button>
  <button type="button" onclick="deleteRow('myTable')">Delete</button>

</body>

</html>

四分之一
<button type="button" onclick="deleteRow('myTable')">Delete</button>

刚刚传入了错误的表 ID。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章