JQuery USES the data of method to read the HTML5 custom attribute data * instance

  • 2020-03-30 02:36:02
  • OfStack

The main methods are as follows:

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

Starting with jQuery 1.4.3, the HTML 5 data- attribute is automatically referenced to the jQuery data object.
For example, HTML:
<div data-role = "page" data-last-value = "43" data-hidden = "true" data-options = '{"name":"John"}' > </div>

The following jQuery code returns true:

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

Unlike the html5 API, jQuery attempts to convert strings into JavaScript values (booleans, Numbers, objects, arrays, and null). If this 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 values of 100), but converting them changes their representation, so they are kept as strings. The string value "100" is converted to the number 100.

If the data (data) attribute is an object (starting with '{') or an array (starting with '['), it can be parsed into a string using jquery.parsejson; it must follow the syntax of valid JSON, including the name of the property with double quotes.

If you want to treat the fetched property value directly as a string, use the attr() method.
Data - attributes are no longer accessed or changed after the first use of the data attribute (all data values are stored in jQuery).
If you call.data() with no arguments, all the data is retrieved as a JavaScript object. 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 the object. In addition, it is faster to manipulate the object directly than to set or get the value every time you call.data().

Related articles: