The main method is as follows:
Copy codeThe Code is as follows:
. Data (key, value)
. Data (obj)
. Data (key)
. Data ()
From jQuery 1.4.3, the data-attribute of HTML 5 will be automatically referenced to the data Object of jQuery.
For example, HTML:
Copy codeThe Code is as follows: <div data-role = "page" data-last-value = "43" data-hidden = "true" data-options = '{"name ": "John"} '> </div>
The following jQuery code returns true:
Copy codeThe Code is as follows:
$ ("Div"). data ("role") = "page ";
$ ("Div"). data ("lastValue") = 43;
$ ("Div"). data ("hidden") === true;
$ ("Div"). data ("options"). name = "John ";
Unlike the html5 api, jQuery tries to convert a string to a JavaScript value (including a Boolean value (booleans), a number (numbers), an object (objects), and an array (arrays) and null )). If this operation does not change the value representation, the value is converted to a number ). For example, "1E02" and "100.000" are equivalent to numbers (number value 100), but convert them to 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 parses it into a string. It must follow the valid JSON syntax, including the attribute name with double quotation marks. If the value cannot be parsed as a JavaScript value, it is retained as a string.
If you want to directly treat the retrieved property value as a string, use the attr () method.
The data-attribute is not accessed or changed after the data attribute is used for the first time (all data values are stored in jQuery ).
If you do not include a parameter when calling. data (), all data is obtained in the form of a JavaScript Object. This object can be securely stored in variables, because once the new object is extracted, the. data (obj) operation on the element will no longer affect this object. In addition, the direct operation on this object is faster than setting or obtaining a value by calling. data () each time.