我想要一个初始没有行的表格,并能够动态创建每一行,也可以删除每一行。但是出现了无法读取未定义的属性'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>
myTable
,而不是tableData
。 - Barmartable.deleteRow(row);
- Kinglish