我正在尝试创建一个允许我使用javascript动态添加和删除行的表。我已经看过其他解决方案,但不能让我的功能相同。我可以添加行但无法删除。
这是我的HTML
<div id="entireRuleSet">
<table border="1" id="newRuleTable">
<tr>
<td>Rule ID</td>
<td>Data Column Name</td>
<td>Operator</td>
<td>Value</td>
<td>Delete</td>
</tr>
<tr>
<td>
<input type="text" id="idBox"/>
</td>
<td>
<input type="text" id="columnBox" />
</td>
<td>
<input type="text" id="operatorBox" />
</td>
<td>
<input type="text" id="valueBox" />
</td>
<td>
<input type="button" id="deleteRow" value="Delete " />
</td>
</tr>
</table>
<input type="button" id="addNewRule" value="Add new rule" onclick="insRow()" />
<input type="button" id="saveButton" value="Save" />
</div>
<br />
<input type="button" id="addNewRuleSet" value="Add new rule set" />
这是我正在使用的javascript
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('newRuleTable').deleteRow(i);
}
function insRow() {
console.log('hi');
var x = document.getElementById('newRuleTable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = 'Delete';
x.appendChild(new_row);
}
答案 0 :(得分:1)
您错过了将 deleteRow(row)
功能绑定到 delete
按钮
<input type="button" id="deleteRow" value="Delete " />
更改为
<input type="button" id="deleteRow" value="Delete " onclick="deleteRow(this)"/>
onclick="deleteRow(this)"
,传递this
,因为您的deleteRow(row)
methid必须参数。
答案 1 :(得分:1)
试试这个
<td>
<input type="button" onclick="deleteRow(this)" id="deleteRow" value="Delete " />
</td>