制作html网页使用dom操作增加或删除表格行
以下是一个示例,演示如何使用DOM操作增加或删除表格行。在这个示例中,我们有一个包含三列的表格,其中第一列包含复选框,第二列包含文本,第三列包含按钮。单击添加按钮将在表格底部添加新行,该行包含一个新的复选框和文本框。单击删除按钮将删除选定的行。
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>表格操作</title>
</head>
<body>
<h1>表格操作</h1>
<table id="myTable">
<tr>
<th></th>
<th>文本</th>
<th>操作</th>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>第一行</td>
<td><button onclick="deleteRow(this)">删除</button></td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>第二行</td>
<td><button onclick="deleteRow(this)">删除</button></td>
</tr>
</table>
<button onclick="addRow()">添加</button>
</body>
</html>
JavaScript代码:
// 获取表格
var table = document.getElementById("myTable");
// 添加行
function addRow() {
// 创建新行
var newRow = table.insertRow(table.rows.length);
// 创建单元格
var checkboxCell = newRow.insertCell(0);
var textCell = newRow.insertCell(1);
var buttonCell = newRow.insertCell(2);
// 添加复选框
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkboxCell.appendChild(checkbox);
// 添加文本框
var text = document.createElement("input");
text.type = "text";
textCell.appendChild(text);
// 添加删除按钮
var button = document.createElement("button");
button.innerHTML = "删除";
button.onclick = function() {
deleteRow(this);
};
buttonCell.appendChild(button);
}
// 删除行
function deleteRow(button) {
var row = button.parentNode.parentNode;
row.parentNode.removeChild(row);
}
该示例中,我们首先获取了表格元素,并定义了两个函数:addRow和deleteRow。addRow函数创建一个新行,然后在该行中创建复选框、文本框和按钮。deleteRow函数获取按钮所在的行,并从表格中删除该行。我们在添加按钮和删除按钮上分别添加了onclick事件处理程序,这样单击按钮时就会调用相应的函数。
原文地址: https://www.cveoy.top/t/topic/Egw 著作权归作者所有。请勿转载和采集!