Original link
The new HTML5 standard allows you to have a common element tag, embed properties like data-* to enable access to some simple data . It is unlimited in number and can be modified dynamically by JavaScript, and CSS selectors are also supported for styling. This makes the data property particularly flexible and very powerful. With this property, we are able to make data presets or storage more orderly and intuitively.
Get its value
Original link
people always like to add custom attributes to the HTML tag to store and manipulate the data. But the problem with this is thatyou don't know if there will be other scripts that will reset your custom attributes., in addition,You do this also cause HTML syntax to not conform to the HTML specification, as well as some other side effects. That's why you've added a custom data property to the HTML5 specification, and you can do a lot of useful things with it. You can read the detailed specification of the HTML5, but the use of this custom data property is very simple: You can add any attribute that begins with "data-" to the HTML tag, which is not displayed on the page, it doesn't affect your page layout and style, but it's readable and writable. The following code fragment is a valid HTML5 tag:
1. Copy the Code
The code is as follows:
<div id= "Awesome" data-myid= "3e4ae6c4e" >some awesome data</div>
But how do you read this data? You can certainly traverse the page elements to read the properties you want, but jquery has built-in methods to manipulate these properties. Use the jquery. Data () method to access these "data-*" properties. One way to do this is. Data (obj), which appears after the jQuery1.4.3 version, which returns the corresponding data property. For example, you can read the Data-myid property value in the following notation:
Copy Code
The code is as follows:
var myid= jQuery ("#awesome"). Data (' myID '); Console.log (myID);
2.
You can also use the JSON syntax in the "data-*" attribute, for example, if you write the following HTML:
Copy Code
The code is as follows:
<div id= "Awesome-json" Data-awesome= ' {"Game": "On"} ' ></div>
You can access this data through JS directly, through the JSON key value, you can get the corresponding value:
Copy Code
The code is as follows:
var gamestatus= jQuery ("#awesome-json"). Data (' awesome '). Game; Console.log (GameStatus);
3.
You can also assign a value directly to the "data-*" property by using the. Data (Key,value) method. One important thing you should be aware of is that these "data-*" attributes should be associated with the element in which it resides, not as a storage tool for storing anything. Although "data-*" is a HTML5 attribute, jquery is generic, so you can use the. Data (obj) method to manipulate "data-*" data in non-HTML5 pages or browsers.
HTML data-* Properties