在 HTML 中,我們常常需要為元素附加一些自訂的屬性來存放額外資訊。JavaScript 提供了幾種讀取與設定這些自訂屬性的方法。本文將透過實例,示範如何靈活操作 HTML 自訂屬性。
以下範例中的 displayName 就是一個自訂屬性:
<input type="text" id="txtBox" displayName="123456" />
可以透過 getAttribute 方法,或是直接存取 attributes 集合來讀取:
document.getElementById("txtBox").getAttribute("displayName");
document.getElementById("txtInput").attributes["displayName"].nodeValue;
設定時則使用 setAttribute 方法,或直接修改 attributes 集合中對應節點的 nodeValue:
document.all.txtBox.setAttribute("displayName", "123456");
document.getElementById("txtInput").attributes["displayName"].nodeValue = "123456";
自訂屬性在存放與元素相關的附加資料時十分方便。值得一提的是,在 HTML5 中,官方建議使用以 data- 為前綴的屬性(例如 data-displayname),並透過 dataset 物件來存取,語意更清晰、也更符合標準規範。希望本文介紹的方法能對你的 JavaScript 程式設計有所幫助。