Use the data-* attribute to embed custom data.
1. Html instance
<ul><li data-animal-type="bird">Owl</li><li data-animal-type="fish">Salmon</li><li data-animal-type="spider">Tarantula</li></ul>
2. browser support
IE Firefox Chrome Safari Opera
Supported
3. Definition and usage
The data-* attribute is used to store private custom data of pages or applications.
Data-* attributes allow us to embed custom data attributes on all HTML elements.
The stored (custom) data can be used in JavaScript on the page to create a better user experience (without Ajax calls or server-side database queries ).
The data-* attribute consists of two parts:
Attribute names should not contain any uppercase letters and must contain at least one character after the prefix "data -"
The property value can be any string.
Note: The user agent ignores the Custom Attributes prefixed with "data.
Syntax
<Element data-* = "somevalue">
Attribute Value
Value description
The value of the property specified by somevalue (in a string ).
HTML adta-* attributes
4. Additional information
HTML tags can be added with custom attributes to store and operate on data. However, this will cause html syntax not to comply with the Html specification.
The HTML5 specification adds a custom data attribute. The usage of the custom data attribute is very simple. 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:
<Div id = "item" data-id = '000000'> 123 </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 code to read the data-id attribute value -- 123:
Var myid = jQuery ("# item"). data ('id ');
You can also use the json syntax in the "data-*" attribute,
<Div id = "item" data-id = '{"game": "on"}'> </div>
You can directly access this data through js, and get the corresponding value through the json key value:
Var gameStatus = jQuery ("# item"). data ('id'). game;
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. Although "data-*" is a property that appears in HTML5, jquery is common. Therefore, you can still use it on non-HTML5 pages or browsers. the data (obj) method is used to operate "data-*" data.