People always like to add custom attributes to HTML tags to store and operate on data. However, you do not know whether other scripts will reset your custom attributes in the future. In addition, if you do this, the html syntax does not conform to the Html specification, and some other side effects are also caused. This is why a custom data attribute is added to the HTML5 specification, and you can use it to do many useful things.
You can read the detailed HTML5 specifications, but the usage of this custom data attribute is very simple, that is, you can add any attribute starting with "data-" to the HTML Tag, these attribute pages are not displayed. They do not affect the layout and style of your pages, but are readable and writable.
The following code snippet is a valid HTML5 Tag:
Copy codeThe Code is as follows:
<Div id = "awesome"
Data-myid = "3e4ae6c4e"> Some awesome data </div>
But how can we read this data? Of course you can traverse the page elements to read the desired attributes, but jquery has built-in methods to operate these attributes. Use jQuery's. data () method to access these "data-*" attributes. One of the methods is. data (obj), which appears after jQuery1.4.3 and can return corresponding data attributes.
For example, you can use the following method to read the data-myid attribute value:
Copy codeThe Code is 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 codeThe Code is as follows:
<Div id = "awesome-json" data-awesome = '{"game": "on"}'> </div>
You can directly access this data through js, and get the corresponding value through the json key value:
Copy codeThe Code is as follows:
Var gameStatus = jQuery ("# awesome-json"). data ('awepartially '). game;
Console. log (gameStatus );
You can also use the. data (key, value) method to directly assign values to the "data-*" attribute. One important thing you should pay attention to is that these "data-*" attributes should be related to the elements in which they are stored. do not regard them as storage tools for storing anything.
Supplement:Although "data-*" is a property that appears in HTML5, jquery is common. Therefore, you can still use it on non-HTML5 pages or browsers. use the data (obj) method to operate "data-*" data