官术网_书友最值得收藏!

Custom data attributes

Another new feature of HTML5 is custom data attributes. Custom data attributes allow you to store custom data private to your application as an attribute on any element in the DOM. All you have to do is prefix the attribute name with data-. The name should be all lower case letters. You can assign any string value to the attribute.

For example, say we had a list of products and we wanted to store information about the products, such as product ID and category. All we have to do is add data-product-id and data-category attributes to the associated elements:

<ul id="product-list">
  <li data-product-id="d1e0ddde" data-category="widgets">
    Basic Widget
  </li>
  <li data-product-id="e6b2c03f" data-category="widgets">
    Super Widget
  </li>
</ul>

So now that we have custom attributes, we can extract the custom data from the elements using JavaScript and use it in our applications. jQuery happens to have a data() method designed just for this purpose. You give it the name of the custom attribute, minus the data-, and it returns the value associated with it.

Continuing with the previous example, let's say we want to allow the user to click on a product in the list and then do some processing on it. The following setSelectedProduct() method uses the data() method to extract the product ID and category from the element that was clicked:

$("#product-list li").click(function() {
    var $product = $(this);
    var productId = $product.data("product-id");
    var category = $product.data("category");
    // Do something...
});
主站蜘蛛池模板: 连平县| 凤山县| 交口县| 涟源市| 佛坪县| 罗甸县| 彩票| 罗源县| 中江县| 和硕县| 四子王旗| 元谋县| 陆丰市| 湘潭县| 棋牌| 昭平县| 贺兰县| 虞城县| 昌邑市| 唐山市| 垣曲县| 峡江县| 泉州市| 阳原县| 平湖市| 浠水县| 贡山| 都昌县| 平塘县| 蓬安县| 阿城市| 鄂伦春自治旗| 陆川县| 安平县| 阳东县| 汝城县| 聂荣县| 奉贤区| 丽水市| 修武县| 芷江|