自定義屬性(俗稱 data 之外的那些自留地)在腳本與樣式之間傳遞信息時很好用。下面以一個帶 displayName 自定義屬性的輸入框為例,說明如何讀取與寫入。
<input type="text" id="txtBox" displayName="123456" />
標準做法是用 getAttribute:
document.getElementById("txtBox").getAttribute("displayName");
也可以繞道 attributes 集合,直接取節點的 nodeValue:
document.getElementById("txtInput").attributes["displayName"].nodeValue;
寫入同樣有兩條路。一是 setAttribute:
document.all.txtBox.setAttribute("displayName", "123456");
二是直接改 attributes 集合裡對應節點的 nodeValue:
document.getElementById("txtInput").attributes["displayName"].nodeValue = "123456";
getAttribute / setAttribute 語義清晰,也是 W3C 標準推薦的接口,兼容性毫無問題,日常開發優先用它。而 attributes[...] 這種走節點的寫法顯得更底層,通常只在需要批量操作屬性集合時才會用到。
另外提醒兩點:document.all 屬於 IE 的歷史遺產,新代碼請一律改用 document.getElementById;而在 HTML5 規範普及後,若只是要存放業務數據,更合適的做法是使用 data-* 屬性並透過 dataset 讀寫,例如 el.dataset.displayName,既語義明確,也不必擔心與原生屬性撞名。