<!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;
????????}
????????var?x=document.getElementsByTagName("li")[0];
????????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>已經是最后一個節點");??????
????????}
????</script>
</body>
</html>
n就是頁面中的某一個元素,在Dom解析中叫做節點(Node)。
解析:
1、var x=n.nextSibling;
nextSibling 屬性返回指定節點之后緊跟的節點,在相同的樹層級中。被返回的節點以 Node 對象返回。
注釋:如果沒有 nextSibling 節點,則返回值為 null。
2、while (x && x.nodeType!=1){
nodeType 屬性返回以數字值返回指定節點的節點類型。
如果節點是元素節點,則 nodeType 屬性將返回 1。
如果節點是屬性節點,則 nodeType 屬性將返回 2。
所以這一句表示:如果n元素后還有緊跟的元素,并且是元素節點的時候,繼續往下找。
3、return x;
直到找不到下一個元素節點的時候,返回x。