Home  >  Article  >  Web Front-end  >  Usage examples of html5's custom data-* attributes and jquery's data() method_jquery

Usage examples of html5's custom data-* attributes and jquery's data() method_jquery

WBOY
WBOYOriginal
2016-05-16 17:24:56916browse

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:

Copy code The code is as follows:

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:
Copy code The code is as follows:

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:
Copy code The code is as follows:



You can directly access this data through js. Through the key value of json, you can get the corresponding value:
Copy code The code is as follows:

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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn