- HTML5 Web Application Development By Example Beginner's Guide
- J.M. Gustafson
- 230字
- 2021-08-13 16:50:27
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... });
- Unity 2020 By Example
- Android和PHP開發(fā)最佳實(shí)踐(第2版)
- JavaScript+jQuery網(wǎng)頁特效設(shè)計任務(wù)驅(qū)動教程(第2版)
- 差分進(jìn)化算法及其高維多目標(biāo)優(yōu)化應(yīng)用
- Linux操作系統(tǒng)基礎(chǔ)案例教程
- Python編程:從入門到實(shí)踐
- Microsoft Dynamics AX 2012 R3 Financial Management
- 微信小程序開發(fā)與實(shí)戰(zhàn)(微課版)
- Java語言程序設(shè)計教程
- 區(qū)塊鏈技術(shù)進(jìn)階與實(shí)戰(zhàn)(第2版)
- Data Science Algorithms in a Week
- Python Web自動化測試設(shè)計與實(shí)現(xiàn)
- Python Deep Learning
- Drupal Search Engine Optimization
- Vue.js 3.x高效前端開發(fā)(視頻教學(xué)版)