js操作表格-添加与删除
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf⑻" />
<title>无标题文档</title>
<script type="text/javascript">
window.onload=function(){
var otab=document.getElementById('tab1');
var obtn=document.getElementById('btn1');
var oname=document.getElementById('name');
var oage=document.getElementById('age');
var id=otab.tBodies[0].rows.length+1;
obtn.onclick=function(){
var otr=document.createElement('tr');
var otd=document.createElement('td');
otd.innerHTML=id++;
otr.appendChild(otd);
var otd=document.createElement('td');
otd.innerHTML=oname.value;
otr.appendChild(otd);
var otd=document.createElement('td');
otd.innerHTML=age.value;
otr.appendChild(otd);
var otd=document.createElement('td');
otd.innerHTML='<a href="javascript:;">删除</a>';
otr.appendChild(otd);
otd.getElementsByTagName('a')[0].onclick=function(){
otab.tBodies[0].removeChild(this.parentNode.parentNode);
};
otab.tBodies[0].appendChild(otr);
};
};
</script>
</head>
<body>
姓名:<input id="name" type="text"/>
年龄:<input id="age" type="text"/>
<input id="btn1" type="button" value="添加"/>
<table id="tab1" border="1" width="500">
<tHead>
<td>ID</td>
<td>姓名</td>
<td>年龄</td>
<td>操作</td>
</tHead>
<tbody>
<tr>
<td>1</td>
<td>he</td>
<td>20</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>ye</td>
<td>21</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td>echo</td>
<td>20</td>
<td></td>
</tr>
</tbody>
</table>
</body>
</html>
------分隔线----------------------------
------分隔线----------------------------