我希望有一个最初没有行的表,然后动态创建每一行并能够删除每一行。
我得到了无法读取未定义的属性“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>
最佳答案
要删除所有行,只需从表中删除 html
function deleteRow(tableID) {
let table = document.getElementById(tableID)
table.innerHTML = "";
}
关于javascript - Html 使用 javascript 动态添加和删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67946453/