DIV CSS 佈局教程網

setAttribute 用法詳解:樣式、事件與跨瀏覽器兼容
編輯:關於JavaScript     

動態給元素添加屬性時,setAttribute() 是最直觀的工具,但它並不像看起來那樣「萬能」——尤其在 class 和事件這兩類屬性上,各瀏覽器的行為並不一致。

基本語法

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

一、樣式問題:class 還是 className

setAttribute("class", value) 中的 class 指的是「class 這個屬性」,所以必須加引號;value 則是具體樣式名。

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) 在 Firefox 中可以正常工作,IE 卻不行——IE 內核不認識 "class",要改用 "className";反過來 Firefox 也不認識 "className"。因此實戰中常見的兼容寫法是兩者並存:

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

二、方法與事件屬性

var bar = document.getElementById("testbt");
bar.setAttribute("onclick", "javascript:alert('This is a test!');");

這裡用 setAttribute 指定 onclick,語義清晰易讀。但 IE 並不支持這種寫法——不是不支持 setAttribute 本身,而是不支持用它設置對象屬性、集合屬性與事件屬性。也就是說 style 和 onclick 這類屬性,在 IE 中通過 setAttribute 設置是行不通的。

三、兼容做法:點符號賦值

為兼顧各瀏覽器,對於對象屬性、集合屬性和事件屬性,直接採用點符號賦值最穩妥:

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

四、選型建議

  • 普通自定義屬性、data-* 屬性,用 setAttribute 沒問題;讀取時配合 getAttribute。
  • class、style、事件處理器一律用點符號賦值,既跨瀏覽器又類型安全。
  • 事件綁定推薦 addEventListener(IE9+),它支持同一事件掛多個處理器,不會互相覆蓋。
  • 給 onclick 賦字符串會引入腳本注入風險,始終優先賦函數。
  • 現代項目中,操作 class 首選 classList.add/remove/toggle,可讀性和兼容性都更好。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved