现在的位置: 首页 > 综合 > 正文

IE8的getElementById不再支持name属性

2012年02月28日 ⁄ 综合 ⁄ 共 573字 ⁄ 字号 评论关闭

这2天发现以前在IE6,IE7等浏览器下运行正常的程序在IE8下都不能正常运行
通过VS.Net调试发现问题所在,IE8的getElementById只支持id,不支持name

在原来IE7及以前的版本中,类似
<input type="text" name="txt1">
都可以使用
var obj = document.getElementById("txt1");来取得对象

IE8中不知道为什么取消了这个功能
var obj = document.getElementById("txt1");
此时obj会等于null

我的解决方法:
// 用$ 代替 document.getElementById
function $(id){
    if (typeof(id)=="object")
        return id;
    if (typeof(id)=="string"){
        var obj = document.getElementById(id);
        if(obj != null)
            return obj;
        obj = document.getElementsByName(id);
        if(obj != null && obj.length > 0)
            return obj[0];
    }
    return null;
}

 

抱歉!评论已关闭.