问题:使用getElementById()取得一个element后,使用setAttribute()设置class在IE中没有反应,alert(getAttribute("class"))得到的结果是null? FireFox中没有问题。
解决:不使用setAttribute而 是直接赋值className就可以设置class的属性了,removeAttribute("class")也没有作用,使用 className=""代替。当然,getAttribute也不行,要取值直接用className就得到了。
Note:如果不是class,而是id, name, src等属性,目前没有这里的兼容性问题
测试代码:
<script type="text/javascript">
function testCompatibility(){
var c = document.getElementById("ab");
// alert(c);
// alert(c.getAttribute("class"));
//var ca =document.createAttribute("class");
//ca.setAttributeNode("a");
alert(c.className+" "+c.getAttribute("class"));
c.className = "a";
alert();
// c.removeAttribute("class");
c.className="";
// c.setAttribute("class","b");
}
</script>
解决:不使用setAttribute而 是直接赋值className就可以设置class的属性了,removeAttribute("class")也没有作用,使用 className=""代替。当然,getAttribute也不行,要取值直接用className就得到了。
Note:如果不是class,而是id, name, src等属性,目前没有这里的兼容性问题
测试代码:
<script type="text/javascript">
function testCompatibility(){
var c = document.getElementById("ab");
// alert(c);
// alert(c.getAttribute("class"));
//var ca =document.createAttribute("class");
//ca.setAttributeNode("a");
alert(c.className+" "+c.getAttribute("class"));
c.className = "a";
alert();
// c.removeAttribute("class");
c.className="";
// c.setAttribute("class","b");
}
</script>
a color:red
b font-weight:bold font-size:20px
a+b color:red font-weight:bold font-size:20px