我有下面的代碼應該在表中生成行,其中每行都有自己的內容和刪除按鈕。無法使用按鈕從動態生成的表中正確刪除行
<!DOCTYPE html>
<html>
<head>
<title>table</title>
</head>
<body>
<input id="inputText">
<button onclick = "addRow()">Add text</button>
<table id = "table">
</table>
<script>
function addRow(){
var newRow = document.createElement("tr");
var col1 = document.createElement("td");
var col2 = document.createElement("td");
newRow.appendChild(col1);
newRow.appendChild(col2);
var button = document.createElement("button");
button.innerHTML = "delete";
button.onclick = function() {
var index = this.parentNode.parentNode.rowIndex;
document.getElementById("table").deleteRow(index);
}
col1.appendChild(button);
var enteredText = document.getElementById("inputText").value;
col2.innerHTML = enteredText;
document.getElementById("table").appendChild(newRow);
}
</script>
</body>
</html>
問題是無論我按哪個刪除按鈕,它都會刪除最後一行。 我試過用console.log(this.parentNode.parentNode)
來查看它是否返回了正確的<tr>
對象,並且確實如此。但由於某種原因,無論按下什麼按鈕,屬性rowIndex
都是-1;因此只有最後一行被刪除。這是否意味着每個動態生成的<tr>
都不知道它的行索引?
什麼是瀏覽器?它適用於我的Firefox,但不適用於Chrome! –
我已經在Chrome和Safari(都爲Mac)上嘗試過它,並且它們都不起作用。 –