<!DOCTYPE html> <html> <head> <title> new document </title> <meta http-equiv="Content-Type" content="text/html; charset=gbk"/> <script type="text/javascript"> window.onload = function(){ Highlight(); } function addOne(obj){ //點擊增長按鈕,增長一行 var tbody = document.getElementById('table').lastChild; var tr = document.createElement('tr'); var td = document.createElement("td"); td.innerHTML = "<input type='text'/>"; tr.appendChild(td); td = document.createElement("td"); td.innerHTML = "<input type='text'/>"; tr.appendChild(td); td = document.createElement("td"); td.innerHTML = "<a href='javascript:;' onclick='deleteRow(this)'>刪除</a>"; tr.appendChild(td); tbody.appendChild(tr); //document.getElementById('table').appendChild(tr); //document.getElementById('table').lastChild.appendChild(tr); var nodes=document.getElementById('table').lastChild.childNodes; console.log(nodes.length); for(var i=0;i<nodes.length;i++){ console.log(nodes[i].nodeType); console.log(nodes[i]); } //console.log(document.getElementById('table').lastChild); Highlight(); } function deleteRow(obj){//點擊刪除,刪除一整行 var tbody = document.getElementById('table').lastChild; console.log(document.getElementById('table')); console.log(tbody); var tr = obj.parentNode.parentNode; tbody.removeChild(tr); } function Highlight(){//鼠標移入背景色改變,移出背景色改變 var tbody = document.getElementById('table').lastChild; trs = tbody.getElementsByTagName('tr'); for(var i =1;i<trs.length;i++){ trs[i].onmouseover = function(){ this.style.backgroundColor ="#f2f2f2"; }; trs[i].onmouseout = function(){ this.style.backgroundColor ="#fff"; } } } </script> </head> <body> <table border="1" width="50%" id="table"> <tr> <th>學號</th> <th>姓名</th> <th>操做</th> </tr> <tr> <td>xh001</td> <td>王小明</td> <td><a href="javascript:;" onclick="deleteRow(this)">刪除</a></td> </tr> <tr> <td>xh002</td> <td>劉小芳</td> <td><a href="javascript:;" onclick="deleteRow(this)">刪除</a></td> </tr> </table> <input type="button" value="添加一行" onclick="addOne()" /> </body> </html>
注意:javascript
table標籤後的子節點有2個,一個是#text ;一個是tbody;而全部的tr是這個tbody的子節點。tbody中的節點:html
發現每一個tr後面都有一個#text節點。java