我有一些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个childNodes,而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标签)以使其防弹?
IE8及以下版本不将空文本节点视为子节点。.children[]
数组从5.5开始在IE中得到支持,可能更早,但在IE8及以下版本中,该数组计数注释节点有轻微错误。只要元素中没有注释(不应该有,HTML注释是不需要的),那么你就可以可靠地使用.children[]