nextElementSibling/nextSibling的可移植性

sym*_*ean 24 javascript nextsibling

我正在写一部手风琴并遇到与IE和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="";
}
Run Code Online (Sandbox Code Playgroud)

这似乎做什么,我期待在MSIE6,FF和铬 - 即初始TR低于nthRow TR元素可见(以前的style.display ="无").

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

(我是Javascript的新手;)

use*_*716 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;
}
Run Code Online (Sandbox Code Playgroud)


Lit*_*eas 9

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

function nextElementSibling(el) {
    if (el.nextElementSibling) return el.nextElementSibling;
    do { el = el.nextSibling } while (el && el.nodeType !== 1);
    return el;
}
Run Code Online (Sandbox Code Playgroud)

这样,我可以避免支持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));
Run Code Online (Sandbox Code Playgroud)