childNodes []无法像IE7和8一样在IE9中工作 [英] childNodes[] not working in IE9 as in IE7 and 8
问题描述
我有一些可在IE7和8中运行的代码,但不适用于9
I have some code that works in IE7 and 8 but not in 9
var table = document.getElementById('RadGrid_ctl01').childNodes[2];
在IE9中不起作用,现在我确实读到IE9计数空格等,因此索引将与IE7和IE8中的索引不同,因此当我将索引从2更改为时,我进行了调试并找到了相同的值4像这样:
which doesn't work in IE9, now I did read that IE9 count white spaces etc and therefore the index won't be the same as in IE7 and IE8 so I debugged and found same values when I changed index from 2 to 4 like so:
var table = document.getElementById('RadGrid_ctl01').childNodes[4];
但是后来我尝试使用此代码访问表对象
However when I later on try to access the table object with this code
var editor = table.childNodes[i].childNodes[j].childeNodes[0]
变量编辑器将在IE7和IE8中获得期望的值,但是在IE9中,由于childNodes [j]没有任何子代,它变为null.我不知道是什么原因造成的. i和j都从0开始.
the variable editor will get the expected value in IE7 and IE8, but in IE9 it becomes null since the childNodes[j] doesn't have any children. I have no idea what causes this. both i and j starts at 0.
有人知道我在做什么错吗?
Anyone know what I am doing wrong?
推荐答案
IE9的行为是正确的,较低的版本是错误的. 问题是由两个html标签之间的空格引起的,该空白应导致进入文本节点.
The behaviour of IE9 is right, lower versions are wrong. The problem is caused by whitespace between two html-tags, which should lead into text-nodes.
更新:添加了示例
<ul><li>Foo</li><li>Bar</li></ul>
<ul>
<li>Foo</li>
<li>Bar</li>
</ul>
看起来几乎一样,不是吗?但是,生成的DOM有所不同. 第一个示例将导致:
Looks pretty much the same, doesn't it? However the resulting DOM differs. First example would result in:
- ul
-- li
--- (text)Foo
-- li
---(text)Bar
第二个标记导致此错误:
While the second Markup leads into this:
- ul
-- (text)
-- li
--- (text)Foo
-- (text)
-- li
--- (text)Bar
-- (text)
由于文本节点不能有任何子节点,因此这会导致Javascript静默失败.
And since text-nodes cannot have any child-nodes, this causes your Javascript to fail silently.
可能的解决方案
一种解决方案是删除空的文本节点.我曾经为此问题写过要点.
One solution is to strip out the empty text-nodes. I once wrote a gist for this issue.
更新:
Node.normalize()
似乎是一种更可靠的解决方案,但我没有检查浏览器的兼容性.
Node.normalize()
seems to be a more reliable solution, but i didn't check it for browser-compatibilty.
这篇关于childNodes []无法像IE7和8一样在IE9中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!