<html>
<head>
<title>Adding and Removing Rows from a table using DHTML and JavaScript</title>
<script language="javascript">
function addRow()
{
var newRow = document.all("tblGrid").insertRow();
//得到表的对象并插入一行,下面是插入了行以后,填充相应的列节点,如下面所示
var oCell = newRow.insertCell();//插入列的节点
oCell.innerHTML = "<input type='text' name='t1'>";//列里面填充的值,innerHtml值列内的所有元素
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t2'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t3'> <input type='button' value='Delete' οnclick='removeRow(this);'/>";
}
function removeRow(src)
{
var oRow = src.parentElement.parentElement; //获取当前事件的父节点
document.all("tblGrid").deleteRow(oRow.rowIndex); //删除当前列
}
</script>
</head>
<body>
<table id="tblGrid" style="table-layout:fixed">
<tr>
<td width="150px">Field1</td>
<td width="150px">Field2</td>
<td width="250px">Field3</td>
</tr>
<tr>
<td><input type="text" name="t1" /></td>
<td><input type="text" name="t2" /></td>
<td><input type="text" name="t3" /> <input type="button" value="Delete" onClick="removeRow(this);" /></td>
</tr>
<tr>
<td><input type="text" name="t1" /></td>
<td><input type="text" name="t2" /></td>
<td><input type="text" name="t3" /> <input type="button" value="Delete" onClick="removeRow(this);" /></td>
</tr>
<tr>
<td><input type="text" name="t1" /></td>
<td><input type="text" name="t2" /></td>
<td><input type="text" name="t3" /> <input type="button" value="Delete" onClick="removeRow(this);" /></td>
</tr>
<tr>
<td><input type="text" name="t1" /></td>
<td><input type="text" name="t2" /></td>
<td><input type="text" name="t3" /> <input type="button" value="Delete" onClick="removeRow(this);" /></td>
</tr>
</table>
<hr>
<input type="button" value="Add Row" onClick="addRow();" />
</body>
</html>