element.firstChild返回'< TextNode ...'而不是FF中的对象 [英] element.firstChild is returning '<TextNode ...' instead of an Object in FF
问题描述
< div id =tabs>
< ul class =tabs>
< li class =current>< a>< span>新闻< / span>< / a>< / li>
< li>< a>< span>影片< / span>< / a>< / li>
< a>< a>< span>照片< / span>< / a>< / li>
< a>< a>< span> Twitter< / span>< / a>< / li>
< / ul>
< / div>
然后,在页面加载的时候,我会放入这个方法:
function processTabs(TabContainer,PageContainer,Index){
var tabContainer = document.getElementById(TabContainer);
var tabs = tabContainer.firstChild;
var tab = tabs.firstChild;
var i = 0;
....更多代码}
其余代码在这个并不重要点,因为它永远不会被调用。 tabContainer设置正确,以引用带有ID标签的div。现在,在我调用tabContainer.firstChild的Internet Explorer中,变量tabs引用我的UL,然后调用var tab = tabs.firstChild;引用我的第一个李。问题是,当我打电话给tabContainer.firstChild Venkman告诉我,它正在返回。所以Firefox正在阅读我的换行符作为真正的孩子在div的!我的UL实际上是childNodes集合中的第二个孩子!
有没有什么办法可以解决这个问题?
谢谢!
你应该跳过 TextNodes
,一个简单的函数can帮助你:
function getFirstChild(el){
var firstChild = el.firstChild; (firstChild!= null&& firstChild.nodeType == 3){//跳过TextNodes
firstChild = firstChild.nextSibling;
}
返回firstChild;
$ / code $ / pre
用法:
var tabContainer = document.getElementById(TabContainer);
var tabs = getFirstChild(tabContainer);
I wrote a tab system using some very basic Javascript and it runs like a champ in IE 8 but, in FireFox 3 I am coming up short. The pertitent HTML is as follows:
<div id="tabs">
<ul class="tabs">
<li class="current"><a><span>News</span></a></li>
<li><a><span>Videos</span></a></li>
<li><a><span>Photos</span></a></li>
<li><a><span>Twitter</span></a></li>
</ul>
</div>
Then, on page load, I get dropped into this method:
function processTabs(TabContainer, PageContainer, Index) {
var tabContainer = document.getElementById(TabContainer);
var tabs = tabContainer.firstChild;
var tab = tabs.firstChild;
var i = 0;
.... more code }
The rest of the code does not matter at this point because it never gets called. tabContainer is set properly to reference the div with the ID tabs. Now, in Internet Explorer when I call tabContainer.firstChild the variable 'tabs' is referencing my UL and then the call var tab = tabs.firstChild; references my first LI. The problem is that when I call tabContainer.firstChild Venkman is telling me it is returning . So firefox is reading my newlines as actual children inside the div's! My UL is actually the second child in the childNodes collection!
Is there any way to fix this?
Thanks!
解决方案 You should skip the TextNodes
, a simple function can help you:
function getFirstChild(el){
var firstChild = el.firstChild;
while(firstChild != null && firstChild.nodeType == 3){ // skip TextNodes
firstChild = firstChild.nextSibling;
}
return firstChild;
}
Usage:
var tabContainer = document.getElementById(TabContainer);
var tabs = getFirstChild(tabContainer);
这篇关于element.firstChild返回'< TextNode ...'而不是FF中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!