IE与Firefox处理Attribute的几点差异

2078次阅读  |  发布于5年以前

前端开发中,经常需要动态的添加、移除或者获取元素的Attribute。也就是说经常会用到setAttribute、removeAttribute和getAt tribute。今天要讨论的是开发中遇到的几处IE与Firefox对Attribute操作的差异。

属性名大小写

在Firefox中,属性没有小写的概念,就算属性名全用大写,Firefox也会解析成小写,用Firebug看就能看到。所以下面的代码在Firefox与IE中 运行结果会不一样。


<div altStr="sss"></div>

    <script type="text/javascript">
     var div = document.getElementsByTagName("div")[0];
     div.removeAttribute("altstr");
     alert(div.getAttribute("altstr"));//IE中返回sss,FF中返回null
    </script>

不过在IE中,removeAttribute有第二个参数,设置为true表示不忽略大小写,为false时忽略大小写,默认值是true;Firefox中因为解 析时就不存在大写属性了,所以就没有第二个参数。也就是说IE中removeAttribute("test",false)等同于Firefox中的removeA ttribute("test"),IE中removeAttribute("test",true)在Firefox中无法实现。

Button的value属性

假设有下面一个button,怎么可以得到button的value属性?


<button value="a">b</button>

其实上,在IE下,无论是btn.getAttribute("value")、btn.value、btn.innerHTML还是btn.innerText都得 "b",但是在Firefox下,btn.getAttribute("value")、btn.value得到的都是"a",btn.innerHTML得到的是" b"。也就是说我们如果要在button上加自定义属性,不要用"value"做属性名,否则在IE下没办法取到值。

getAttribute返回值类型不同

看一下下面的代码,你认为IE与Firefox分别会返回什么?


<button onclick="alert(0)">b</button>

    <script type="text/javascript">
     var btn = document.getElementsByTagName("button")[0];
     alert(btn.getAttribute("onclick"));
    </script>

IE下,getAttribute("onclick")返回的是一个function,直接可以调用,Firefox下则返回一个string,直接调用会出错。

题外话

今天翻手册,看到上面对Button标签是这么描述的:

BUTTON 元素在表单中提交的话,Microsoft® Internet Explorer 5 及以后版本将提交 VALUE 标签属性,若存在的话。否则就提交 innerText 属性。在 Internet Explorer 4.0 中,只会提交 innerText 值。

但是我发现我的IE8对于form中的button,无论有没有value属性,都是提交button的innerHTML属性。不知道是什么回事。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8