我們經常需要在JavaScript中給Element動態添加各種屬性,可以使用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、onclick
bar.setAttribute("onclick", "");這里利用setAttribute指定onclick屬性,簡單很好理解。但是IE不支持。
為達到兼容各種瀏覽器的效果,可以用點符號來設置Element的對象屬性、集合屬性和事件屬性。
document.getElementById("foo").className = "fruit"; document.getElementById("foo").style.cssText = "color: #00f;"; document.getElementById("foo").style.color = "#00f"; document.getElementById("foo").onclick= function () { alert("This is a test!"); }