表格应用--tBodies tHead tFoot rows cells
<title>无标题文档</title> <script> window.onload=function () { var oTab=document.getElementById('tab1'); // alert(oTab.getElementsByTagName('tbody')[0].getElementsByTagName('tr')[1].getElementsByTagName('td')[1].innerHTML); alert(oTab.tBodies[0].rows[1].cells[1].innerHTML); } </script> </head> <body> <table id="tab1" border="1" width="500"> <thead> <td>ID</td> <td>姓名</td> <td>年龄</td> </thead> <tbody> <tr> <td>1</td> <td>blue</td> <td>23</td> </tr> <tr> <td>2</td> <td>张三</td> <td>24</td> </tr> <tr> <td>3</td> <td>李四</td> <td>25</td> </tr> <tr> <td>4</td> <td>王五</td> <td>26</td> </tr> </tbody> </table> </body>
隔行变色,选中高亮
<title>无标题文档</title> <script> window.onload=function () { var oTab=document.getElementById('tab1'); var oldColor=''; for(var i=0;oTab.tBodies[0].rows.length;i++) { oTab.tBodies[0].rows[i].onmouseover=function () { oldColor=this.style.background; this.style.background='yellow'; } oTab.tBodies[0].rows[i].onmouseout=function () { this.style.background=oldColor; } if(i%2) { oTab.tBodies[0].rows[i].style.background=''; } else { oTab.tBodies[0].rows[i].style.background='green'; } } } </script> </head> <body> <table id="tab1" border="1" width="500"> <thead> <td>ID</td> <td>姓名</td> <td>年龄</td> </thead> <tbody> <tr> <td>1</td> <td>blue</td> <td>23</td> </tr> <tr> <td>2</td> <td>张三</td> <td>24</td> </tr> <tr> <td>3</td> <td>李四</td> <td>25</td> </tr> <tr> <td>4</td> <td>王五</td> <td>26</td> </tr> </tbody> </table> </body>
添加、删除一行,还有id号的处理(一般ID号不复用,删除了就不再用了)
<title>无标题文档</title> <script> 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=oAge.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>blue</td> <td>23</td> <td></td> </tr> <tr> <td>2</td> <td>张三</td> <td>24</td> <td></td> </tr> <tr> <td>3</td> <td>李四</td> <td>25</td> <td></td> </tr> <tr> <td>4</td> <td>王五</td> <td>26</td> <td></td> </tr> </tbody> </table> </body>
重剑无锋,大巧不工