<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>nextSibling</title> </head> <body> <ul id="u1"> <li id="a">javascript</li> <li id="b">jquery</li> <li id="c">html</li> </ul> <ul id="u2"> <li id="d">css3</li> <li id="e">php</li> <li id="f">java</li> </ul> <script type="text/javascript"> function get_nextSibling(n){ var x=n.nextSibling; while (x && x.nodeType!=1){ x=x.nextSibling; } return x; } function get_previousSibling(n){ var x=n.previousSibling; while(x && x.nodeType!=1){ x=x.previousSibling; } return x; } var x=document.getElementsByTagName("li")[1]; document.write(x.nodeName); document.write(" = "); document.write(x.innerHTML); var y=get_nextSibling(x); if(y!=null){ document.write("<br />nextsibling: "); document.write(y.nodeName); document.write(" = "); document.write(y.innerHTML); }else{ document.write("<br>已经是最后一个节点"); } var z=get_previousSibling(x); if(z!=null){ document.write("<br />previoussibling: "); document.write(z.nodeName); document.write(" = "); document.write(z.innerHTML+"<br />"); }else{ document.write("<br>已经是第一个节点"); } </script> </body> </html>
当 var x=document.getElementsByTagName("li")[2];时:
当当 var x=document.getElementsByTagName("li")[3];时:
当当 var x=document.getElementsByTagName("li")[4];时:
请问这是什么原因?
该题中,getElementsTagName 获得的数组元素有6个li,但分布在两个不同层级,而nextSibling和previousSibling只能操作同一树层级的节点!所以前两次都是正常显示!
copy你的代码运行一下,当 var x=document.getElementsByTagName("li")[4];时的显示结果应该是:
LI = php
nextsibling: LI = java
previoussibling: LI = css3
中间有个空行