<!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-8" /> <title>表格功能扩展</title> <script> window.onload=function () { var oName=document.getElementById('name'); var oAge=document.getElementById('age'); var oBtn=document.getElementById('btn'); var oTab=document.getElementById('tab'); var num=oTab.tBodies[0].rows.length+1; //alert(oTab.getElementsByTagName('tbody')[0].getElementsByTagName('tr')[1].getElementsByTagName('td')[1].innerHTML ); //alert(oTab.tBodies[0].rows[1].cells[1].innerHTML );//表格的简便操作,等同于上面的语句 setInterval(function()//100毫秒刷新一下颜色,要不是添加的都是无颜色的 { var color; for(var i=0;i<oTab.tBodies[0].rows.length;i++) { oTab.tBodies[0].rows[i].onmouseover=function () { color=this.style.background; this.style.background='green'; } oTab.tBodies[0].rows[i].onmouseout=function () { //this.style.background=color; } if(!(i%2)) { oTab.tBodies[0].rows[i].style.background='#ccc'; } else { oTab.tBodies[0].rows[i].style.background=''; } } },100); setInterval(function ()//每一秒刷新一次,能够让删除键起作用 { var aa=oTab.getElementsByTagName('a'); for(var i=0;i<aa.length;i++) { aa[i].onclick=function() { oTab.tBodies[0].removeChild(this.parentNode.parentNode); } } },1000); oBtn.onclick=function () { var oTr=document.createElement('tr'); var oTd=document.createElement('td');//创建td标签 oTd.innerHTML=num++;//id号加一位 oTr.appendChild(oTd);//标签添加到父节点 var oTd=document.createElement('td');//同理 oTd.innerHTML=oName.value; oTr.appendChild(oTd); var oTd=document.createElement('td'); oTd.innerHTML=oAge.value; oTr.appendChild(oTd); var oTd=document.createElement('td'); oTd.innerHTML='<a href="javascript:;">删除</a>';//在操作框中添加删除标签 oTr.appendChild(oTd); oTab.tBodies[0].appendChild(oTr);//将tr标签添加到主表格中 } } </script> </head> <body> 姓名:<input id="name" type="text"/> 年龄:<input id="age" type="text"/> <input id="btn" type="button" value="添加"/> <table id="tab" border="2px" width="500px"> <thead> <td>ID</td> <td>姓名</td> <td>年龄</td> <td>操作</td> </thead> <tbody> <tr> <td>1</td> <td>张三</td> <td>14</td> <td><a href="javascript:;">删除</a></td> </tr> <tr> <td>2</td> <td>李四</td> <td>15</td> <td><a href="javascript:;">删除</a></td> </tr> <tr> <td>3</td> <td>王五</td> <td>19</td> <td><a href="javascript:;">删除</a></td> </tr> <tr> <td>4</td> <td>xiaoqiang</td> <td>11</td> <td><a href="javascript:;">删除</a></td> </tr> </tbody> </table> </body> </html>