Home > Web Front-end > JS Tutorial > Use the data() method in jQuery to read HTML5 custom attributes data-*example_jquery

Use the data() method in jQuery to read HTML5 custom attributes data-*example_jquery

WBOY
Release: 2016-05-16 16:52:37
Original
1037 people have browsed it

The main methods are as follows:

Copy code The code is as follows:

.data( key , value )
.data( obj )
.data( key )
.data()

Starting with jQuery 1.4.3, the HTML 5 data- attribute will automatically be referenced to jQuery in the data object.
For example HTML:
Copy code The code is as follows:

The following jQuery code is It returns true:
Copy code The code is as follows:

$ ( "div" ). data ( "role" ) === "page" ;
$ ( "div" ) . data ( "lastValue" ) === 43 ;
$ ( "div" ) . data ( "hidden" ) === true ;
$ ( "div" ) . data ( "options" ) . name === "John" ;

Different from the html5 api, jQuery will try Convert a string to a JavaScript value (including booleans, numbers, objects, arrays, and null). If doing so does not change the representation of the value, the value is converted to a number. For example, "1E02" and "100.000" are equivalent to numbers (numeric value 100), but converting them would change their representation, so they are retained as strings. The string value "100" is converted to the number 100.

If the data attribute is an object (starting with "{") or an array (starting with '['), you can use jQuery.parseJSON to parse it into a string; it must follow the syntax of valid JSON, Include the property name in double quotes. If the value cannot be parsed as a JavaScript value, it will be retained as a string.


If you want to use the retrieved attribute value directly as a string, please use the attr() method.
The data-attribute is no longer accessed or changed after the first use of this data attribute (all data values ​​are stored internally in jQuery).
If you call .data() without parameters, all data will be obtained in the form of JavaScript objects. This object can be safely stored in a variable, because once the new object is extracted, subsequent .data(obj) operations on the element will no longer affect this object. Additionally, manipulating this object directly is faster than calling .data() each time to set or get a value.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template