【问题标题】:Portability of nextElementSibling/nextSiblingnextElementSibling/nextSibling 的可移植性
【发布时间】:2011-07-01 13:42:15
【问题描述】:

我目前正在编写一个手风琴,遇到了与nextSibling difference between IE and FF? 中描述的相同的问题 - 特别是 Microsoft 的 nextSibling / nextElementSibling 与其他人实现的区别。

由于各种原因,使用 jquery 不是一种选择。也不是让我所有的 MS 用户都升级到 MSIE9

目前我正在使用以下代码来解决该问题:

// tr is a TR doc element at entry....
while (nthRow--) {
     // for Chrome, FF tr=tr.nextElementSibling; for MSIE...tr=tr.nextSibling;
     tr=tr.nextElementSibling ? tr.nextElementSibling : tr=tr.nextSibling;
     if (!tr || tr.nodeName != "TR") {
            break;
     }
     tr.style.display="";
}

这似乎符合我在 MSIE6、FF 和 Chrome 中的预期 - 即初始 TR 下方的 nthRow TR 元素可见(以前为 style.display="none")。

但这可能会产生意想不到的副作用吗?

(我是 Javascript 的新手;)

【问题讨论】:

    标签: javascript nextsibling


    【解决方案1】:

    nextSibling 会看到 HTML 代码 cmets,因此请务必将它们拒之门外。

    除此之外,您应该没问题,因为您的 tr 元素之间不会有任何文本节点。

    我能想到的唯一其他问题是Firefox 3,其中nextElementSibling 尚未实施。因此,如果您支持该浏览器,则需要手动模拟nextElementSibling(很确定他们已经在 FF3.5 中实现了它。)

    创建nextElementSibling() 函数会更安全:

    tr = tr.nextElementSibling || nextElementSibling(tr);
    
    function nextElementSibling( el ) {
        do { el = el.nextSibling } while ( el && el.nodeType !== 1 );
        return el;
    }
    

    【讨论】:

    • 是的 - 这似乎是一个更好的解决方案 - 实际上与 epascarello 的答案相同,但这个更强大
    • ...不应该是 while ( el && el.nodeType !== 1 ); ?
    • @symcbean:确实如此。固定的。接得好。 :o)
    【解决方案2】:

    考虑到以前的答案,我目前正在以这种方式实现它以授予跨浏览器兼容性:

    function nextElementSibling(el) {
        if (el.nextElementSibling) return el.nextElementSibling;
        do { el = el.nextSibling } while (el && el.nodeType !== 1);
        return el;
    }
    

    这样,我可以避免支持 nextElementSibling 的浏览器的 do/while 循环。 也许我太害怕 JS 中的 WHILE 循环了 :)

    此解决方案的一个优点是可递归性:

    //this will always works:
    var e = nextElementSibling(nextElementSibling(this));
    
    //this will crash on IE, as looking for a property of an undefined obj:
    var e = this.nextElementSibling.nextElementSibling || nextElementSibling(nextElementSibling(this));
    

    【讨论】:

      【解决方案3】:

      Firefox nextSibling 返回空格 \n 而 Internet Explorer 不返回。

      在引入 nextElementSibling 之前,我们必须这样做:

      var element2 = document.getElementById("xxx").nextSibling;
      while (element2.nodeType !=1)
      {
                element2 = element2.nextSibling;
      } 
      

      【讨论】:

        猜你喜欢
        • 2015-09-14
        • 2013-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多