JavaScript: 为表格插入或删除行
首先,要了解一下HTML DOM 中的方法:deleteRow(index): 从表格删除指定位置的行;
deleteCell(index): 从行中删除指定位置的一格;
insertRow(index): 在表格指定位置插入新行;
insetCell(index): 为行内部指定位置插入一格;
innerHTML: 设置或者返回指定位置的开始标签与结束标签之间的HTML内容;
rowIndex: 返回该行在表中的位置;
parentNode: 返回父节点;
插入行:
function insertRowForTable(tableId){var tableNode = document.getElementById(tableId);var newRow = tableNode.insertRow(-1);newRow.insertCell(-1).innerHTML = newRow.rowIndex;newRow.insertCell(-1).innerHTML = "<input type = 'button' value = 'delete' onclick = deleteRowFromTable(this) />";}
删除行:
function deleteRowFromTable(rowNode){var row = rowNode.parentNode.parentNode;var tableId = row.parentNode.parentNode.id;var index = row.rowIndex;document.getElementById(tableId).deleteRow(index);}
测试页面:
<!--To change this template, choose Tools | Templatesand open the template in the editor.--><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript"> function insertRowForTable(tableId) { var tableNode = document.getElementById(tableId); var newRow = tableNode.insertRow(-1); newRow.insertCell(-1).innerHTML = newRow.rowIndex; newRow.insertCell(-1).innerHTML = "<input type = 'button' value = 'delete' onclick = deleteRowFromTable(this) />"; } function deleteRowFromTable(rowNode) { var row = rowNode.parentNode.parentNode; var tableId = row.parentNode.parentNode.id; var index = row.rowIndex; document.getElementById(tableId).deleteRow(index); } </script> </head> <body> <input type ="button" value ="add"/> <table id="myTable"> </table> </body></html>
页:
[1]