JavaScript中setAttribute用法

來源:互聯網
上載者:User

 

我們經常需要在JavaScript中給Element動態添加各種屬性,這可以通過使用setAttribute()來實現,這就涉及到了瀏覽器的相容性問題。

setAttribute(string name, string value):增加一個指定名稱和值的新屬性,或者把一個現有的屬性設定為指定的值。

1、樣式問題

setAttribute("class", value)中class是指改變"class"這個屬性,所以要帶引號。

vName代表對樣式賦值。

例如:

var input = document.createElement("input");

input.setAttribute("type", "text");

input.setAttribute("name", "q");

input.setAttribute("class",bordercss);

輸出時:<input type="text" name="q" class="bordercss">,即,input控制項具有bordercss樣式屬性

注意:class屬性在W3C DOM中扮演著很重要的角色,但由於瀏覽器差異性仍然存在。

使用setAttribute("class", vName)語句動態設定Element的class屬性在firefox中是行的通的,但在IE中卻不行。因為使用IE核心的瀏覽器不認識"class",要改用"className";

同樣,firefox 也不認識"className"。所以常用的方法是二者兼備:

element.setAttribute("class", value); //for firefox

element.setAttribute("className", value); //for IE

 

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!"); }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.