Some time ago, my colleagues complained about the. data () method in jQuery in the group:
XXX (NNNNNNN) 15:11:34
<A id = "a" data-xxx = "00123" type = "codeph" text = "codeph"/>
Alert ($ ('# A'). data ('xxx'); // 123
Unreliable data method
XXX (NNNNNNN) 15:13:17
Honestly, attr ('data-XXX') has carefully studied the description of the. data () method in the jQuery document:
Copy codeThe Code is as follows:
As of jQuery 1.4.3 HTML 5 data-attributes will be automatically pulled in to jQuery's data object.
The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5
Specification.
For the following instructions:
Copy codeThe Code is as follows:
<Div data-role = "page" data-last-value = "43" data-hidden = "true" data-options = '{"name ": "John"} '> </div>
$ ("Div"). data ("role") = "page ";
$ ("Div"). data ("lastValue") = 43;
$ ("Div"). data ("hidden") === true;
$ ("Div"). data ("options"). name = "John ";
When using. data () to obtain a value, jQuery first tries to convert the obtained string value to the JS type, including Boolean value, null, number, object, and array:
If the value is "true | false", the corresponding Boolean value is returned;
If the value is "null", return null;
If the value is a string composed of pure numbers (+ data + "= data), the corresponding number (+ data) is returned );
If the value is (? : \ {[\ S \ S] * \} | \ [[\ s \ S] * \]) $, for example, "{key: value}" or [1, 2, 3], then try jQuery. parse parseJSON;
Otherwise, a string value is returned.
Of course, this document also specifically states that if you want to obtain the string value instead of the value for automatic conversion, you can use. attr ("data-" + key) to obtain the corresponding value:
Copy codeThe Code is as follows:
To retrieve the value's attribute as a string without any attempt to convert it, use the attr () method.
JQuery source code is as follows:
Copy codeThe Code is as follows:
Function dataAttr (elem, key, data ){
// If nothing was found internally, try to fetch any
// Data from the HTML5 data-* attribute
If (data = undefined & elem. nodeType = 1 ){
// RmultiDash =/([A-Z])/g
Var name = "data-" + key. replace (rmultiDash, "-$1"). toLowerCase ();
Data = elem. getAttribute (name );
If (typeof data = "string "){
Try {
/* The data (key) method tries to convert the obtained value to the JS type, including Boolean value, null, number, object, array */
Data = "true "? True:
Data = "false "? False:
Data = "null "? Null:
// Only convert to a number if it doesn't change the string
+ Data + "" = data? + Data:
/* Rbrace = /(? : \ {[\ S \ S] * \} | \ [[\ s \ S] * \]) $ /,*/
Rbrace. test (data )? JQuery. parseJSON (data ):
Data;
} Catch (e ){}
// Make sure we set the data so it isn't changed later
JQuery. data (elem, key, data );
} Else {
Data = undefined;
}
}
Return data;
}