開心生活站

位置:首頁 > IT科技 > 

js,setattribute

IT科技3.22W

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

js setattribute

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!"); }
標籤:js setattribute