setAttribute()方法参数问题
先看遇到的问题:setAttribute demo(分别在FF和IE下运行)
今天在同学机子上使用IE7查看,发现动态创建的Iframe,有边框 。在iframe标签中设置frameborder=“0”,即可去除边框,无论ff 、ie都是正确的,但是动态添加在IE下貌似就不起作用了,可是我上面已经使用setAttribute(“frameborder”, “0″),来去除边框了,并且在FF下也显示正常,为这个问题折腾我2个多小时。
分别查看Firebug和IE developer toolbar中的Dom,才发现,在火狐中Dom属性为frameBorder,而IE中显示的是frameborder,将代码改为
f.setAttribute("frameBorder","0");
显示正确!下面了解下这个方法:
object.setAttribute(sName, vValue [, iFlags])
sName参数应是Dom属性而非html中的属性,这里我一直存在误解,以为sName和html中属性名相同,以后要切记! 原来一直设置单个单词属性,也没出现什么问题。现在frameborder是个双字节属性,问题就出来了。Dom中Html专有的接口属性应该以小写字母开头,如果属性有多个单词构成,第二个单词以及接下来的每个单词的首字母都要大写。
因此以后如果设置input,maxlength属性就应写成“setAttribute(‘maxLength’,’50′)”而非maxlength。另外比较特殊的是设置class属性,dom中我们用HTMLElement的className属性,在这里按上面说的应写成setAttribut(‘className’,'c’)在IE下正确,但FF下并不行,FF认识class。
所以可以两者兼备
element.setAttribute("class", value); //for firefox
element.setAttribute("className", value); //for IE
但似乎并不如直接设置elements.className=value;来的方便,还是建议用这条,这里只是指出一下问题。
另外再说一下iflags参数:
| iFlags | Optional. Integer that specifies one the following flags: | |
| 0 | When the attribute is set, it overwrites any attributes with the same name, regardless of their case. | |
| 1 | Default. The case of the attribute that you set is respected when it is set on the object. | |
0,覆盖任何同名属性(忽略大小写)
1,默认。覆盖已经被设定的属性值
所以,上面的问题我也可以setAttribute(‘frameborder’,’0′,0)实现。
相关参考:
Pingback: 随便写的一个Node代码 | 西红柿花园