理解DOM的一个例子

<!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>

  注意:

table标签后的子节点有2个,一个是#text ;一个是tbody;而所有的tr是这个tbody的子节点。tbody中的节点:

发现每个tr后面都有一个#text节点。

 

posted @ 2018-03-22 22:16  potato~e-e  阅读(115)  评论(0编辑  收藏  举报