People always like to add custom attributes to the HTML tags to store and manipulate the data. The problem with this is that you don't know if any other scripts will reset your custom attributes in the future, and in addition, you can also cause HTML syntax to be inconsistent with HTML specifications and some other side effects. This is why adding a custom data attribute to the HTML5 specification allows you to do a lot of useful things with it.
You can read the detailed specification of HTML5, but the use of this custom data property is very simple, that you can add any attribute on the HTML tag that starts with "data-", which is not displayed on the page and does not affect the layout and style of your page, but it is readable and writable.
one of the following code snippets is a valid HTML5 tag:
Copy Code code 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 attributes you want, but jquery has built-in methods to manipulate these attributes. Use the. Data () method of jquery to access these "data-*" properties. One of the methods is. Data (obj), which appears after the jQuery1.4.3 version, and it returns the corresponding data property.
For example, you can read the Data-myid attribute value in the following notation:
Copy Code code as follows:
var myid= jQuery ("#awesome"). Data (' myID ');
Console.log (myID);
You can also use the JSON syntax in the "data-*" attribute, for example, if you write the following HTML:
Copy Code code as follows:
<div id= "Awesome-json" Data-awesome= ' {game ': ' On '} ' ></div>
You can access this data directly through JS, and you can get the corresponding value through the key value of JSON:
Copy Code code as follows:
var gamestatus= jQuery ("#awesome-json"). Data (' awesome '). Game;
Console.log (GameStatus);
You can also assign values directly to the "data-*" property by using the. Data (Key,value) method. One important thing to note is that these "data-*" attributes should be associated with the element in which it resides, not as a storage tool for storing anything.
Add:Although "data-*" is a HTML5 attribute, jquery is generic, so you can still use the. Data (obj) method to manipulate "data-*" data in a non-HTML5 page or browser