DIV CSS 佈局教程網

setAttribute 用法與它在 IE 中的相容問題
編輯:JavaScript基礎知識     

setAttribute(name, 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">,也就是該控制項套用了 bordercss 樣式。注意 class 是屬性名稱,要加引號。

但這裡有相容問題:Firefox 認得 class,IE 不認;IE 只認 className,Firefox 又不認。常見做法是兩者都寫:

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

二、事件與 style 屬性在 IE 中設不進去

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

IE 並非不支援 setAttribute 這個函式,而是不允許用它設定某些類別的屬性——物件屬性、集合屬性、事件屬性都在此列。也就是說,用 setAttribute 設定 style 或 onclick 在 IE 中行不通。

三、相容做法:直接用點號赋值

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

這幾行程式碼在各瀏覽器都能正常運作,因此實務上更值得採用。

今日的建議

舊版 IE 的這些限制已隨其退場而失去意義,但有幾點仍然值得注意:

  • 設定自訂資料請用 dataset(el.dataset.userId = "1"),它會正確對應到 data-user-id 屬性。
  • 讀寫 class 建議用 classList 的 add/remove/toggle/contains,避免直接覆寫字串而抹掉其他 class。
  • 事件綁定請用 addEventListener,不要用 setAttribute("onclick", ...)——字串形式等於隱含一次 eval,且無法一次綁多個處理器。
  • 若屬性值可能包含使用者輸入或不安全內容,請留意 setAttribute 不會執行 javascript: 協定,但把它設到 href 上仍有風險,需自行過濾。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved