表格外设置一个按钮根据id去删除表格内的某一行
时间: 2024-02-20 11:58:38 浏览: 18
好的,针对您的问题,您可以参考以下代码实现:
HTML代码:
```html
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John Doe</td>
<td><button onclick="deleteRow(1)">Delete</button></td>
</tr>
<tr>
<td>2</td>
<td>Jane Doe</td>
<td><button onclick="deleteRow(2)">Delete</button></td>
</tr>
<tr>
<td>3</td>
<td>Bob Smith</td>
<td><button onclick="deleteRow(3)">Delete</button></td>
</tr>
</tbody>
</table>
```
JavaScript代码:
```javascript
function deleteRow(id) {
var table = document.getElementById("myTable");
for (var i = 0; i < table.rows.length; i++) {
if (table.rows[i].cells[0].innerHTML == id) {
table.deleteRow(i);
break;
}
}
}
```
在这段代码中,我们首先获取了表格对象和要删除的行的id。然后我们遍历表格中的每一行,找到与传入的id相匹配的行,然后使用`deleteRow()`方法删除该行。
请注意,为了使代码更简洁,我将按钮的单击事件直接绑定到了JavaScript函数`deleteRow()`上,而不是使用`addEventListener()`方法来添加事件侦听器。在实际应用中,最好使用后者,因为这样可以更好地将HTML和JavaScript分离开来。
相关推荐
![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)