setAttribute方法

1.element 要用 getElementById or ByTagName 来得到,

2.setAttribute("class", vName) class 是指改变 "class" 这个属性,所以要带引号。

3.IE 中要把 class 改成 className,.....IE 不认 class, 所以最好写两句,都用上吧。

W3C DOM - {setAttribute()}

setAttribute(string name, string value) :增加一个指定名称和值的新属性,或者把一个现有的属性设定为指定的值。

 

1 、关于 class className

class 属性在 W3C DOM 中扮演着很重要的角色,但由于浏览器差异性仍然存在。使用 setAttribute("class", vName) 语句动态设置

Element class 属性在 firefox 中是行的通的,在 IE 中却不行。因为使用 IE 内核的浏览器不认识 "class" ,要改用 "className"

同样, firefox  也不认识 "className" 。所以常用的方法是二者兼备:

   element.setAttribute("class", vName);

   element.setAttribute("className", vName);  //for IE

 

2 setAttribute() 的差异

我们经常需要在 JavaScript 中给 Element 动态添加各种属性,这可以通过使用 setAttribute() 来实现,这就涉及到了浏览器的兼容性问题。

var bar = document.getElementById("foo");

bar.setAttribute("onclick", "javascript:alert('This is a test!');");

这里利用 setAttribute 指定 e onclick 属性,简单,很好理解。但是 IE 不支持, IE 并不是不支持 setAttribute 这个函数,

而是不支持用 setAttribute 设置某些属性,例如对象属性、集合属性、事件属性,也就是说用 setAttribute 设置 style onclick 这些属性

IE 中是行不通的。为达到兼容各种浏览器的效果,可以用点符号法来设置 Element 的对象属性、集合属性和事件属性。

document.getElementById("foo").className = "fruit";

document.getElementById("foo").style.cssText = "color: #00f;";

document.getElementById("foo").style.color = "#00f";

document.getElementById("foo").οnclick= function () { alert("This is a test!"); 、

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值