J**aScript中setAttribute用法介绍

时间:2016.04.19 发布人:XTQING269

J**aScript中setAttribute用法介绍

已解决问题

谷歌XTQING269用户在2016.04.19提交了关于“长风J**aScript中setAttribute用法介绍”的提问,欢迎大家涌跃发表自己的观点。目前共有1个回答,最后更新于2024-12-04T07:28:47。希望大家能够帮助她。

详细问题描述及疑问:期待您的答案,当代劳模,所有人都应该向你学习 !

希望以下的回答,能够帮助你。

第1个回答

用户名:riyghe  

我们点南簧布市给火齐好经常需要在J**aScript中给Element动态添加各种属性,这可以通过使用setAttribute()来实现,这就涉及到了浏览器的兼容性问题

setAttribute(stringname,str得ingvalue):增加一个指定名称和值的新属性,或者把一个现有的属性设定为指室定的值。
1、样式问题
setAttribute("class",value)中class是指改变"class"这个属性问答,所以要带引号。
vName代表对样式赋值。
例如:

复制代码代码如下:
varinput=document.createElement("input");
inpu米富到演状金晶杨展t.setAttribu分束稳松划组似且硫死te("type","text");
input.setAttribute("name","q");
input.setAttribute("class",bordercss);


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

复制代码代码如下:
element.setAttribute("class",value);//forfirefox
element.setAttribute("className",value);//forIE


2、方法属性等问似以亲往严运斗未航白能题
例如:

复制代码代码如下:
varbar=document.getElementById("testbt");
bar.se段第特清两tAttribute("onclick","javascript:alert('Thisisatest!');");


这里利用setAttribute指定e的onclick属性,简单,很好理解。
但是IE不支持,IE并不是不支空果形史持setAttribute这个函数,而是不支持用setAttribute设置某些属性,例如对象属性、集合属性、事件属性,也就是说用setAttribute设置style和onclick这些属性在IE中是行不通的。
为达到兼容各种浏览器的效果,可以用点符号法来设置Element的对象属性、集合属性和事件设将屋孩染今绍附燃属性。

复制代码代码如下:


document.getEl满开运核微带ementById("te晚势stbt").className="bordercss";
document.getElementB并护征yId("testbt")觉宣距功谁什起东食敌.style.cssText="color:#00f早块离;";
docume比杂族减再应鱼运渐nt.getElementById("testbt").style.color="#00f";
document.getElemen普培观散跑海食重tById("testbt").onclick=function(){alert("Thisisatest!");}