nextSibling和previousSibling中浏览器的兼容问题

来源:互联网 发布:司法考试网络课程 编辑:程序博客网 时间:2024/05/17 02:32

在使用nextSibling和previousSibling查找下一个、上一个元素时,会碰到IE和火狐的浏览器兼容问题。

注释:Internet Explorer 会忽略节点间生成的空白文本节点(例如,换行符号),而 Mozilla 不会这样做。

元素节点的节点类型是 1,因此如果首个子节点不是一个元素节点,它就会移至下一个节点,然后继续检查此节点是否为元素节点。整个过程会一直持续到首个元素子节点被找到为止。通过这个方法,我们就可以在 Internet Explorer 和 Mozilla 得到正确的方法。(主要通过检查下一个要查找的元素的nodeType==1);

元素节点的nodeType 1;属性节点的nodeType为2;文本节点的nodeType为3;……

function get_nextsibling(n)  {  var x=n.nextSibling;  while (x.nodeType!=1)   {   x=x.nextSibling;   }  return x;  }

实用案例:

html代码

 <ul id="lis"> <li>糖醋排骨</li>    <li>圆笼粉蒸肉</li>    <li>泡菜鱼</li>    <li id="myLove">板栗烧鸡</li>    <li>麻婆豆腐</li> </ul>

js脚本:

<script type="text/javascript">/* function get_nextsibling(n)  {  var x=n.nextSibling;  while (x.nodeType!=1)   {   x=x.nextSibling;   }  return x;  }function findDom(){var love = document.getElementById("myLove");var next = love.nextSibling;var pre = get_nextsibling(love);//alert(next);alert(love.childNodes[0].nodeValue+"+/+."+pre.childNodes[0].nodeValue);}*/function nextSib(node){var tempLast = node.parentNode.lastChild;if(node == tempLast){return null;}var tempObj = node.nextSibling;while(tempObj.nodeType != 1 &&tempObj.nextSibling != null){tempObj = tempObj.nextSibling;}return (tempObj.nodeType==1) ? tempObj:null;}function preSib(node){var tempFirst = node.parentNode.firstChild;if(node == tempFirst){return null;}var tempObj = node.previousSibling;while(tempObj.nodeType != 1 && tempObj.previousSibling != null){tempObj = tempObj.previousSibling;}return (tempObj.nodeType==1 )? tempObj:null;}function findDom(){var myItem = document.getElementById("myLove");var nextListItem = nextSib(myItem);var prev = preSib(myItem);alert("下一项"+((nextListItem!=null)?nextListItem.firstChild.nodeValue:null)+"前一项"+((prev!=null)?prev.firstChild.nodeValue:null));}</script>