我正在编写手风琴并遇到nextSibling difference between IE and FF?中描述的相同问题 - 特别是微软的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的新手;)
答案 0 :(得分:28)
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;
}
答案 1 :(得分: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));
答案 2 :(得分:4)
Firefox nextSibling返回空格\ n,而Internet Explorer则没有。
在介绍nextElementSibling之前,我们必须做这样的事情:
var element2 = document.getElementById("xxx").nextSibling;
while (element2.nodeType !=1)
{
element2 = element2.nextSibling;
}