我写了一些代码来制作动态表格。插入数据部分可以正常工作。但是我无法使用删除按钮删除该行,因为它位于innerHTML内部。
有没有人有想法?我无法理解。
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td")
//insert row with data
function myCreateFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(tr.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
var cell4 = row.insertCell(3);
cell1.innerHTML = document.getElementById("fname").value;
cell2.innerHTML = document.getElementById("lname").value;
cell4.innerHTML = '<button type = "button">Delete</button>'
if(document.getElementById("myRadio").checked){
cell3.innerHTML = document.getElementById("myRadio").value
} else {
cell3.innerHTML = document.getElementById("myRadio2").value
}
document.getElementById("fname").value = null;//form with no value
document.getElementById("lname").value = null;//form with no value
document.getElementById("myRadio").checked = false;//form with no value
document.getElementById("myRadio2").checked = false;//form with no value
}
答案 0 :(得分:0)
您可以使用deleteRow()函数
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
table, td {
border: 1px solid black;
}
<table id="myTable">
<tr>
<td>Row 1</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 2</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 3</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
</table>
你可以像这样附上。
cell4.innerHTML = '<button type = "button" onclick="deleteRow(this)">Delete</button>';