setAttribute()函数的用法详解:
在动态创建元素设置元素的属性的时候setAttribute()函数用处很大,它可以动态的设置元素的属性,下面介绍一下它的用法。
语法结构:
setAttribute(name, value)
1).name表示要设置的属性。
2).value表示属性值。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /><head><title>蚂蚁部落</title><style type="text/css">#mytest{ width:100px; height:100px; background-color:green;}</style><script type="text/javascript">window.onload=function(){ var odiv=document.createElement("div"); odiv.setAttribute("id","mytest"); document.body.appendChild(odiv);}</script></head><body></body></html>
以上代码创建了一个div元素,并且使用setAttribute()函数设置此元素的id属性,然后使用id选择器设置div的样式。
setAttribute的用法基本如此,但是此函数具有浏览器兼容性问题,比如在IE7和IE6等低版本的浏览器中设置元素的class属性就存在,这里就不多介绍了,具体可以参阅IE6和IE7是否支持setAttribute()函数一章节。
原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=8307
更多内容可以参阅:http://www.softwhy.com/javascript/
原标题:setAttribute()函数的用法详解
关键词:函数