在實際開發中,我們常常需要為 HTML 元素加上自訂屬性來存放額外的資料,並透過 JavaScript 動態讀取或修改。本文就來說明如何操作這些自訂屬性。
以下面這段 input 為例,其中 displayName 就是我們自訂的屬性:
<input type="text" id="txtBox" displayName="123456" />
要讀取元素上的自訂屬性,有兩種常見寫法:
document.getElementById("txtBox").getAttribute("displayName");
document.getElementById("txtInput").attributes["displayName"].nodeValue
第一種透過 getAttribute 直接傳入屬性名稱;第二種則是存取元素的 attributes 集合,再取出對應節點的 nodeValue。
寫入自訂屬性的方式同樣有兩種:
document.all.txtBox.setAttribute("displayName", "123456");
document.getElementById("txtInput").attributes["displayName"].nodeValue = "123456";
setAttribute 是最直覺的方法,只要傳入屬性名與值即可;另一種則是直接改寫 attributes 集合中該節點的 nodeValue。
掌握以上技巧,就能在 JavaScript 程式中靈活地讀寫 HTML 元素的自訂屬性了。