html中点击按钮删除表格中选中的行
时间: 2024-04-30 12:23:39 浏览: 21
以下是一个示例代码,可以通过点击按钮删除表格中选中的行。需要注意的是,这个示例代码假设你已经有了一个表格,并且每一行的第一个单元格是一个复选框,用于选择要删除的行。
```html
<table id="myTable">
<tr>
<th>Select</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>John</td>
<td>25</td>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>Jane</td>
<td>30</td>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>Bob</td>
<td>40</td>
</tr>
</table>
<button onclick="deleteRows()">Delete Selected Rows</button>
<script>
function deleteRows() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
var checkbox = rows[i].getElementsByTagName("input")[0];
if (checkbox && checkbox.checked) {
table.deleteRow(i);
i--; // decrement i to account for the deleted row
}
}
}
</script>
```
这个代码通过`document.getElementById`方法获取名为"myTable"的表格,然后通过`getElementsByTagName`方法获取所有的行。接着,它遍历每一行,并且获取该行的第一个单元格中的复选框。如果复选框被选中,那么就调用`table.deleteRow(i)`删除该行。由于删除一行后,后面的行会往前移动一个位置,因此需要将`i`减1以避免跳过一个行。最后,点击按钮时会调用`deleteRows`函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)