People always like to add custom attributes to HTML tags to store and manipulate data. But the problem with doing this is that you don't know if other scripts will reset your custom attributes in the future. In addition, if you do this, it will also cause the html syntax to not comply with the Html specification, as well as some other side effects. That's why a custom data attribute was added to the HTML5 specification, and you can do a lot of useful things with it.
You can read the detailed specifications of HTML5, 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 It is not displayed, it will not affect your page layout and style, but it is readable and writable.
The following code snippet is a valid HTML5 markup:
data-myid="3e4ae6c4e">Some awesome data
However, How to read this data? You can of course iterate through the page elements to read the properties you want, but jQuery already has built-in methods for manipulating these properties. Use jQuery's .data() method to access these "data-*" properties. One of the methods is .data(obj). This method appeared after jQuery 1.4.3. It can return the corresponding data attribute.
For example, you can read the data-myid attribute value using the following writing method:
var myid= jQuery("#awesome").data('myid');
console.log(myid);
you You can also use json syntax in "data-*" attributes, for example, if you write the following html:
You can directly access this data through js. Through the key value of json, you can get the corresponding value:
var gameStatus= jQuery("#awesome-json").data('awesome').game;
console.log(gameStatus);
You can also directly assign values to the "data-*" attributes through the .data(key,value) method. An important thing you need to pay attention to is that these "data-*" attributes should be related to the element they are in, and do not use them as storage tools to store anything.
Supplement: Although "data-*" is an attribute that only appears in HTML5, jquery is universal, so you can still use it in non-HTML5 pages or browsers. data(obj) method to operate "data-*" data