【问题标题】:How to deal with different childNode count by IE8 vs all other browsers如何通过 IE8 与所有其他浏览器处理不同的 childNode 计数
【发布时间】:2013-05-18 19:25:09
【问题描述】:

我有许多想要使用事件来操作的 div,例如添加/删除类、属性等。我有嵌套元素。起初我使用的是children 集合,但由于支持不佳,我转向childNodes

但是,现在我对其进行了测试,并提示检查childNodes 的数量,例如,我得到了在所有其他浏览器中为 39,在 IE8 中为 20。这使得循环不可靠,我需要检查类。我的 Javascript:

function removeOnclick(){
    var parent = document.getElementById('selections');
    var parent_length = parent.childNodes.length;
    alert(parent_length);
    for (var i=0; i<39; i+=2){
    if (parent.childNodes[i].hasAttribute("onclick")) {
        parent.childNodes[i].removeAttribute("onclick");
        }
    }
}

使用这种 HTML 格式,所有浏览器都将它们计为 20(我没有粘贴所有 20 个节点):

<div id="selections"><div id="selection1" class="size" onclick="count(this.id);" onmouseover="onovershowpop(this.id);" onmouseout="onouthidepop(this.id);"><div class="pop">sample</div></div></div>

但是使用这种格式,所有其他浏览器都算 39 个 childNode,而 IE8 仍然算 20:

<div id="selections">  
    <div id="selection1" class="size" onclick="count(this.id);" onmouseover="onovershowpop(this.id);" onmouseout="onouthidepop(this.id);">
        <div class="pop">sample</div>
    </div>
</div>

是否每次都必须进入一行(div标签)才能使其防弹?

【问题讨论】:

  • 你不能只使用parent_length而不是文字39吗?
  • 你能发布你的html吗?大多数现代浏览器会将某些标签之间的空白视为文本节点;我不相信 IE8 会。不过看到它会有所帮助。
  • 确实,因为我的代码中已经有 parent_length 我可以..但仍然..因为 ie8 不计算空节点,在浏览器识别 39 个节点的一次实例中我必须在每个循环中将 i 增加 2,而在 IE8 中我必须将其增加 1..
  • .children[] 自 IE5.5 起已受支持...为什么它不适合您?

标签: javascript internet-explorer internet-explorer-8 cross-browser


【解决方案1】:

IE8 及以下不将空文本节点计为子节点。 .children[] 数组自 5.5 甚至更早版本就已在 IE 中得到支持,但该数组计算 IE8 及更低版本中的注释节点时存在轻微错误。只要元素中没有 cmets(不应该有,永远不需要 HTML cmets),那么您就可以可靠地使用 .children[]

【讨论】:

  • so children[],会在所有浏览器中返回与现有元素相同的结果吗?
  • 是的,假设没有 HTML cmets。
  • 正如你正确提到的,我没有任何 html cmets,我不应该..我只是复制了我的文件,用子节点替换子节点,这似乎比让我的整个嵌套更清洁的解决方案div 成一行.. 非常感谢..
猜你喜欢
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 2012-08-10
  • 2011-03-28
  • 1970-01-01
  • 2019-11-24
  • 2013-11-02
相关资源
最近更新 更多