Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

javascript - Portability of nextElementSibling/nextSibling

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.

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="";
}

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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.)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...