DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
HTML5 實戰:自定義資料屬性的建立與存取
編輯:HTML和Xhtml     

HTML5 開發正如火如荼,自定義屬性逐漸受到開發者青睞,並在 Web 語意中發揮重要作用。本文透過實作案例,說明如何建立與存取 HTML5 自定義資料屬性。

建立 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 當作頁面功能的做法仍言之過早,畢竟不少瀏覽器尚未支援。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved