带有表格和按钮的 HTML:
<div>
<h1>Info</h1>
<form>
<table id="t">
<tr>
<th></th>
<th>index</th>
<th>name</th>
<th>job</th>
<th>date</th>
<th>department</th>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>1</td>
<td>Alex</td>
<td>Hacker</td>
<td>100000000000000000</td>
<td>2</td>
</tr>
</table>
<br/>
<input type="submit" value="delete" onclick="deleteRow()">
</form>
</div>
我想删除已建立复选框的行。单击按钮即可删除。
应该删除的 Javascript 函数:
function deleteRow() {
let table = document.getElementById('t')
let boxs = table.getElementsByTagName("input")
for (i = 0; i < boxs.length; i++){
if(boxs[i] == true) {
table.deleteRow((boxs[i].parentNode.parentNode).rowIndex)
}
}
}
我调试了这段代码,数组的大小定义正确,但没有进入条件。
最佳答案
在您的代码中,您无需进行太多更改。 您需要像下面这样更改 if 语句。
来自
if(boxs[i] == true) {
}
给
if(boxs[i].checked == true) {
}
因为 box[i] 是对象。 所以如果你想获得检查状态,你需要调用 boxes[i].checked。这会给你真/假。
function deleteRow() {
let table = document.getElementById('t')
let boxs = table.getElementsByTagName("input")
for (i = 0; i < boxs.length; i++){
if(boxs[i].checked == true) {
table.deleteRow((boxs[i].parentNode.parentNode).rowIndex)
}
}
return false;
}
<div>
<h1>Info</h1>
<form onsubmit="return deleteRow()">
<table id="t">
<tr>
<th></th>
<th>index</th>
<th>name</th>
<th>job</th>
<th>date</th>
<th>department</th>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>1</td>
<td>Alex</td>
<td>Hacker</td>
<td>100000000000000000</td>
<td>2</td>
</tr>
</table>
<br/>
<input type="submit" value="delete">
</form>
</div>
关于javascript - 单击按钮时如何删除表格中的一行?使用Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465634/