nextElementSibling / nextSibling的可移植性 [英] Portability of nextElementSibling/nextSibling

查看:153
本文介绍了nextElementSibling / nextSibling的可移植性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写手风琴并遇到与 nextSibling中描述的问题相同的问题IE和FF之间的差异? - 特别是微软的nextSibling / nextElementSibling与其他人实现的差异。

I'm currently writing an accordion and running into the same problem as described in nextSibling difference between IE and FF? - specifically differences between Microsoft's nextSibling / nextElementSibling and that implemented by everyone else.

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

For various reasons, using jquery is not an option. Nor is getting all my MS users to upgrade to MSIE9

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

Currently I'm using the following code to work around the problem:

// 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)。

Which seems to do what I expect in MSIE6, FF and Chrome - i.e. the nthRow TR elements below the initial TR are made visible (previously style.display="none").

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

But is this likely to have unexpected side effects?

(我是Javascript的新手;)

(I'm a bit of a newbie with Javascript ;)

推荐答案

nextSibling 会看到HTML代码注释,所以请务必将其保留。

nextSibling will see HTML code comments, so be sure to keep them out.

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

Other than that you should be alright since you won't have any text nodes between your tr elements.

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

The only other issue I could think of would be in Firefox 3 where nextElementSibling hadn't yet been implemented. So if you're supporting that browser, you'll need to manually emulate nextElementSibling. (Pretty sure they had it implemented in FF3.5 though.)

创建会更安全nextElementSibling() function:

You'll be safer to create a nextElementSibling() function:

tr = tr.nextElementSibling || nextElementSibling(tr);

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

这篇关于nextElementSibling / nextSibling的可移植性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆