IE的document.all返回值不稳定的问题

最近在改造旧的应用,发现有些操作时灵时不灵,如:
     window.document.all("ChargedByAdCode").value="350100"
有时正常,有时无效。
经过长时间摸索,终于找到原因:
1)旧页面的元素,可能出于浏览器兼容考虑,既有ID、也有name(除radio外都相同)。
2)初次调用window.document.all时,IE按照ID读取,返回的是单一元素,因此
    window.document.all("ChargedByAdCode").value
能对指定元素赋值。
3)随后的互动脚本中调用了document.getElementsByName("ChargedByAdCode"),
此脚本返回的是元素集合
4)再次调用window.document.all时,IE就不是按照ID读取,而是按照Name--返回的是元素集合,因此
     window.document.all("ChargedByAdCode").value
是undefined,任何操作失败。
在IE6、9(标准模式、兼容视图)下结果相同。在Firefox13下没有此类问题。
个人觉得:页面Javascript中应尽量避免使用window.document.all,应以getElementById代替,只有在checkbox等多选元素(name相同)处理时才使用getElementsByName。
演示范例:
<form >
<input type="text" value="data" id="storenode" name="storenode"/>
<button οnclick="ie_test()">ie_test</button>
</form>
<script language=javascript>
function ie_test()
{
//初次访问window.document.all("storenode")按ID取出元素
alert("1.初次访问window.document.all,按ID取出元素:"+window.document.all("storenode").value);

//无实际意义的getElementsByName调用未对window.document.all造成影响
window.document.getElementsByName("storenode");
if(window.document.all("storenode").value===undefined){
  alert("2.不可能的情况!");
}
else{
  alert("2.无实际意义的getElementsByName调用未对window.document.all造成影响,仍然按ID取出元素:"+window.document.all("storenode").value);
}
//赋值-有意义的getElementsByName调用对window.document.all造成影响,按name取出collection
var aa=window.document.getElementsByName("storenode");
if(window.document.all("storenode").value===undefined){
  alert("3.赋值-有意义(?)的getElementsByName调用对window.document.all造成影响,按name取出的是collection,其长度为:"+window.document.all("storenode").length);
}
else{
  alert("3.Firefox的结果--window.document.all不受getElementsByName影响,仍然按ID取出元素:"+window.document.all("storenode").value);
}

//赋值-有意义的getElementByid调用对window.document.all造成影响,按ID取出元素
var bb=window.document.getElementById("storenode");
if(bb.value===undefined){
  alert("4.不可能的情况。");
  return;
}
if(window.document.all("storenode").value===undefined){
  alert("4.getElementById无法扭转getElementsByName调用对window.document.all造成影响,按name取出的是collection,其长度为:"+window.document.all("storenode").length);
}
else{
  alert("4.Firefox的结果--window.document.all仍然按ID取出元素:"+window.document.all("storenode").value);
}
}
</script>
IE测试情况:

图片

图片

图片

图片

图片

firefox测试情况

图片

图片

图片

图片

图片

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值