HTML5 開發正如火如荼,自定義屬性逐漸受到開發者青睞,並在 Web 語意中發揮重要作用。本文透過實作案例,說明如何建立與存取 HTML5 自定義資料屬性。
可先建立一個基本骨架:
<!DOCTYPE html> <html> <head> <script> /*functions here*/ </script> </head> <body> </body> </html>
在 body 中設定自定義元素,在 head 的 script 區域用 JavaScript 存取。
先加入一些內容與自定義屬性,並給個 ID 以便辨識:
<div id="product1" data-product-category="clothing"> Cotton Shirt </div>
自定義屬性的形式為「data-*」,在「data-」後接自訂名稱。這是 HTML5 中唯一有效且能通過驗證的做法。命名方式取決於項目細節,例如這個範例可套用於不同產品類別的零售網站。自定義屬性能讓你以特殊方式透過 JavaScript 設定元素,例如做動畫顯示;若沒有標準 HTML 元素可用,就建議使用自定義屬性。
<input type="button" value="get attribute" onclick="getElementAttribute('product1')" />
最常用的方法是 getAttribute:
function getElementAttribute(elemID) {
var theElement = document.getElementById(elemID);
var theAttribute = theElement.getAttribute('data-product-category');
alert(theAttribute);
}
也可以用元素的 dataset 取代 DOM 的 getAttribute,在需要遍歷多個屬性時可能更有效率,但瀏覽器對 dataset 的支援仍偏低:
//var theAttribute = theElement.getAttribute('data-product-category');
var theAttribute = theElement.dataset.productCategory;
透過 dataset 存取時會移除「data-」前綴,且若名稱含連字符會轉為駝峰式,例如「data-product-category」變成「productCategory」。
可用 DOM 方法或 dataset 刪除屬性:
//DOM method
theElement.removeAttribute('data-product-category');
//dataset version
theElement.dataset.productCategory = null;
結語:在 HTML5 中實作自定義屬性技術上並不複雜,真正困難的是判斷所用方法是否適合你的項目、又該如何發揮最大效益。請記得,目前把 dataset 當作頁面功能的做法仍言之過早,畢竟不少瀏覽器尚未支援。