在HTML表单中动态计算表中的行和列操作可以通过JavaScript来实现。以下是一个示例代码,展示了如何动态添加和删除表格的行和列。
动态添加行:
<!DOCTYPE html>
<html>
<head>
<script>
function addRow() {
var table = document.getElementById("myTable");
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "New Row";
cell2.innerHTML = "New Row";
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
<br>
<button onclick="addRow()">Add Row</button>
</body>
</html>
动态添加列:
<!DOCTYPE html>
<html>
<head>
<script>
function addColumn() {
var table = document.getElementById("myTable");
for (var i = 0; i < table.rows.length; i++) {
var cell = table.rows[i].insertCell(table.rows[i].cells.length);
cell.innerHTML = "New Column";
}
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
<br>
<button onclick="addColumn()">Add Column</button>
</body>
</html>
动态删除行:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteRow() {
var table = document.getElementById("myTable");
if (table.rows.length > 1) {
table.deleteRow(table.rows.length - 1);
}
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
<br>
<button onclick="deleteRow()">Delete Row</button>
</body>
</html>
动态删除列:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteColumn() {
var table = document.getElementById("myTable");
for (var i = 0; i < table.rows.length; i++) {
if (table.rows[i].cells.length > 1) {
table.rows[i].deleteCell(table.rows[i].cells.length - 1);
}
}
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
<br>
<button onclick="deleteColumn()">Delete Column</button>
</body>
</html>
这些示例代码演示了如何通过JavaScript在HTML表单中动态计算表中的行和列操作。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云