找回密码
 新建账号

[JS] JS setAttribute getAttribute 陷阱

[复制链接]
php 发表于 2014/4/21 01:14 | 显示全部楼层 |阅读模式
Javascript的setAttribute和getAttribute函数分别用来设置和获取HTML元素的属性,既可以是元素原生支持的属性,比如id,name,value等,也可以设置原本不存在的自定义属性,如data-value。
但要注意有一些陷阱:
  • 使用setAttribute设置CSS类名
    在IE6-8中,如果要设置元素的CSS类名(即HTML元素的class="className"属性),在标准浏览器(Google Chrome, Firefox, Safari, Opera, IE9+等,下同)中应该这样写:
    object.setAttribute('class','className');//设置CSS类名,相当于object.className='className';
    var className=object.getAttribute('class);//获取CSS类名,相当于var className=object.className;
    在IE6-8中要这样写:
    object.setAttribute('className','className'); //设置CSS类名
    object.setAttribute('className'); //获取CSS类名
  • 使用setAttribute设置CSS属性值为布尔值
    如果用setAttribute设置了一个属性的值为布尔值,在标准浏览器中使用getAttribute()取到的值是字符串的"true"或"false",而不是布尔值true或false,在IE6-8中取回来的是布尔值,和设置的值一样。
  • 除了setAttribute设置属性getAttribute获取属性值外,还可以用removeAttribute来移除属性,很多人出现removeAttribute('class')失败的现象,是因为CSS类在IE6-8中的属性名是className,而不是class,所以正确的写法是removeAttribute('className')。

手机版|轻松E站

GMT+8, 2024/4/19 13:30

快速回复 返回顶部 返回列表