var tbody = document.getElementById('table').lastChild; var trs = tbody.getElementsByTagName('tr');
如上 target获取的是table下的最后一个子节点也就是最后一个<tr></tr>标签
那么为什么trs要在最后一个tr标签下获取tr标签呢?
源代码如下
<!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(){ var tbody = document.getElementById('table').lastChild; var 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"; } } } 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); } function deleteRow(obj){ var tbody = document.getElementById('table').lastChild; var tr = obj.parentNode.parentNode; tbody.removeChild(tr); } </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>
table的子节点结构是text和tbody
var tbody = document.getElementById('table').lastChild; 这句话是获取tbody,所有tr和td都在tbody中