js中setAttribute用法详解

jssetAttribute基本用法

element.setAttribute(attributename,attributevalue)

setAttribute() 方法添加指定的属性,并为其赋指定的值,看到w3c的例子

document.getElementsByTagName("INPUT")[0].setAttribute("type","button");

我们经常需要在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!"); }

例子

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Untitled Document</title>
        <script language="JavaScript">
            function change() {
                var input = document.getElementById("li1");
                alert(input.getAttribute("title"));
                input.setAttribute("title", "mgc");
                alert(input.getAttribute("title"));
            }
        </script>
    </head>
    <body>
        <ul id="u">
            <li id="li1" title="hello">Magci</li>
            <li>J2EE</li>
            <li>Haha!</li>
        </ul>
        <input type="button" value="Change" onClick="change();" />
    </body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章