24

我目前正在编写手风琴并遇到与IE 和 FF 之间的 nextSibling 区别中描述的相同问题?- 特别是微软的 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 的新手;)

4

3 回答 3

30

nextSibling将看到 HTML 代码注释,因此请务必将它们排除在外。

除此之外,您应该没问题,因为您的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;
}
于 2011-07-01T14:06:03.977 回答
9

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

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));
于 2012-11-15T19:39:51.153 回答
4

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

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

var element2 = document.getElementById("xxx").nextSibling;
while (element2.nodeType !=1)
{
          element2 = element2.nextSibling;
} 
于 2011-07-01T14:03:15.383 回答