[转]使用Javascript动态增加,删除表格(使用DHTML对象模型)

<html>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<head>

<script language="javascript">
function deleteRow(index){
var tableObj=document.getElementById("mytable");
tableObj.deleteRow(index);
}
function addRow(){
var tableObj=document.getElementById("mytable");
var newRowObj=tableObj.insertRow(tableObj.rows.length);
var newColName=newRowObj.insertCell(newRowObj.cells.length);
var newColAge=newRowObj.insertCell(newRowObj.cells.length);
var newColButton=newRowObj.insertCell(newRowObj.cells.length);

newColName.innerHTML=document.getElementById("newName").value;
newColAge.innerHTML=document.getElementById("newAge").value;
newColButton.innerHTML='<input type="button" value="删除" onclick="deleteRow('+(tableObj.rows.length-1)+')">';
}
</script>
</head>

<body>
<table width="100%" id="mytable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>操作</td>
</tr>
<tr>
<td>gaoxiang</td>
<td>28</td>
<td><input type="button" onclick="deleteRow(0)" value="删除"/></td>
</tr>
<tr>
<td>gaoxiang</td>
<td>28</td>
<td><input type="button" onclick="deleteRow(1)" value="删除"/></td>
</tr>
</table>

<input type="text" name="name" id="newName" />
<input type="text" name="age" id="newAge"/>
<input type="button" onclick="addRow();" value="新增"/>
</body>
</html>

你可能感兴趣的:(JavaScript)