上次讲到了如何动态给表格增加行,那么这次就讲讲如何删除表格的行了。首先建立一个表格,
<table border="1">
<tr>
<td>姓名</td>
<td>地址</td>
</tr>
<tbody id="mainbody">
<tr id="delCell">
<td>name</td>
<td>address</td>
</tr>
</tbody>
</table>
取得tbody的元素var mailbody = document.getElementById("mainbody");,
接着取得要删除行的元素var cell = document.getElementById("delCell");
最后就是从tbody中移去要删除的行就可以了mainbody.removeChild(cell);
完整的代码如下:
<html>
<head>
<title>动态删除表格的行</title>
<script type="text/javascript">
function deleteCell(){
var mailbody = document.getElementById("mainbody");
var cell = document.getElementById("delCell");
if(cell!=undefined){
mainbody.removeChild(cell);
}
}
</script>
</head>
<body>
<table border="1">
<tr>
<td>姓名</td>
<td>地址</td>
</tr>
<tbody id="mainbody">
<tr id="delCell">
<td>name</td>
<td>address</td>
</tr>
</tbody>
</table>
<input type="button" value="删除" onclick="deleteCell()"/>
</body>
<html>