建站优化

当前位置:

js setattribute

浏览量:75次

js setattribute

js中的setattribute是什么?有什么作用?一起来看看阳泰小编今天的分享吧。

setattribute的作用就是增加一个指定名称和值的新属性,或者把一个现有的属性设定为指定的值。在JavaScript中,如果要给Element动态添加各种属性,就需要通过使用setAttribute()来实现。

下面是具体示例:

1、样式问题
setAttribute("class", value)中class是指改变"class"这个属性,所以要带引号。

var input = document.createElement("input");input.setAttribute("type", "text");input.setAttribute("name", "q");input.setAttribute("class",bordercss);

输出时:,即,input控件具有bordercss样式属性
注意:class属性在W3C DOM中扮演着很重要的角色,但由于浏览器差异性仍然存在。
使用setAttribute("class", vName)语句动态设置Element的class属性在firefox中是行的通的,但在IE中却不行。因为使用IE内核的浏览器不认识"class",要改用"className";
同样,firefox 也不认识"className"。所以常用的方法是二者兼备:

element.setAttribute("class", value); //for firefoxelement.setAttribute("className", value); //for IE

2、方法属性等问题

var bar = document.getElementById("testbt");bar.setAttribute("onclick", "javascript:alert('This is a test!');");

这里利用setAttribute指定e的onclick属性,但是IE不支持,IE并不是不支持setAttribute这个函数,而是不支持用setAttribute设置某些属性,例如对象属性、集合属性、事件属性,也就是说用setAttribute设置style和onclick这些属性在IE中是行不通的。
为达到兼容各种浏览器的效果,可以用点符号法来设置Element的对象属性、集合属性和事件属性。

document.getElementById("testbt").className = "bordercss";document.getElementById("testbt").style.cssText = "color: #00f;";document.getElementById("testbt").style.color = "#00f";document.getElementById("testbt").onclick= function () { alert("This is a test!"); }

[声明]本网转载网络媒体稿件是为了传播更多的信息,此类稿件不代表本网观点,本网不承担此类稿件侵权行为的连带责任。故此,如果您发现本网站的内容侵犯了您的版权,请您的相关内容发至此邮箱【779898168@qq.com】,我们在确认后,会立即删除,保证您的版权。