<table id="tableID">
<tr>
<th>Attr</th>
<th>Val</th>
</tr>
<td>
<input type="checkbox" name="firstChk" />
</td>
<td>
<input type="text" name="firstAttr" />
</td>
<td>
<input type="text" name="firstVal" />
</td>
</table>
<input type="button" value="Add A Row" onclick="javascript: addARow('tableID')" />
<input type="button" value="Delete" onclick="javascript: deleteARow('tableID')" />
这个单独的js文件被调用:
function deleteARow(tID) {
try {
var tableObj = document.getElementById(tID);
var numRows = tableObj.rows.length;
// starts at 1 because never delete row that holds table headers
for(var index=1; index < numRows; index++) {
var rowObj = tableObj.rows[index];
// rowObj.cells[0] gives the td, then childNodes[0] gives checkbox element
var chkboxObj = rowObj.cells[0].childNodes[0];
if(null != chkboxObj && true == chkboxObj.checked) {
tableObj.deleteRow(index);
/* next 2 lines are necessary because DOM's tr indices shift back
* with a deletion
*/
numRows--;
index--;
}
} // end for
} // end try
catch(e) {
alert(e);
}
} // end function
此代码可以在单击“删除”按钮后删除任何行和任意数量的行,对于具有复选框的第一行(xpath为// table / tr [1]的那一行)除外。我已经多次手动跟踪代码并且无法对其进行调试,所以我已经发布了我的评论代码。
代码有什么问题?我希望我能弄明白如何在firebug中使用js调试器:(
答案 0 :(得分:1)
您的代码存在一些问题。
首先,您桌子的标记格式不正确。您有td
个没有父tr
的。{/ p>
其次,用于获取checkbox对象的逻辑未返回复选框。因此,当您点击if
语句时,chkboxObj.checked
返回了undefined
。
这是更新/工作代码:
<强> HTML 强>
<table id="tableID">
<tr>
<th>Attr</th>
<th>Val</th>
</tr>
<tr>
<td>
<input type="checkbox" name="firstChk" />
</td>
<td>
<input type="text" name="firstAttr" />
</td>
<td>
<input type="text" name="firstVal" />
</td>
</tr>
</table>
<input type="button" value="Add A Row" onclick="addARow('tableID')" />
<input type="button" value="Delete" onclick="deleteARow('tableID')" />
<强>的JavaScript 强>
function deleteARow(tID) {
try {
var tableObj = document.getElementById(tID);
var numRows = tableObj.rows.length;
// starts at 1 because never delete row that holds table headers
for (var index = 1; index < numRows; index++) {
var rowObj = tableObj.rows[index];
// rowObj.cells[0] gives the td, then childNodes[0] gives checkbox element
// This was not returning the checkbox element. See updated code:
// Get first input in row - this will be the checkbox
var chkboxObj = rowObj.cells[0].getElementsByTagName("input")[0];
if (chkboxObj != null && chkboxObj.checked == true) {
tableObj.deleteRow(index);
/* next 2 lines are necessary because DOM's tr indices shift back
* with a deletion
*/
numRows--;
index--;
}
} // end for
} // end try
catch (e) {
alert(e);
}
} // end function
此外,这里是a working fiddle。