jQuery.data() Method
Example
Store and retrieve data on a div element.
Definition and Usage
The $.data() function is used to store and retrieve data associated with the specified DOM element, returning the set value.
Note: 1. This is a low-level method. The .data() method is more convenient to use.
2. Data stored and retrieved via the data() function is temporary. Once the page is refreshed, all previously stored data will be removed.
3. This method does not currently provide cross-platform setting on XML documents. Internet Explorer does not allow attaching data via custom attributes in XML documents.
Syntax
Usage 1
$.data( element, key, value )
Note: 1. Data stored and retrieved via the data() function is temporary. Once the page is refreshed, all previously stored data will be removed.
2. undefined is an unrecognized data value. Calling jQuery.data( el, "name", undefined ) will return the corresponding "name" data, equivalent to jQuery.data(el, "name" ).
We can set different values on an element and retrieve these values:
jQuery.data(document.body, 'foo', 52);
jQuery.data(document.body, 'bar', 'test');
Usage 2
$.data( element, key )
We can set different values on an element and retrieve these values:
alert(jQuery.data( document.body, 'foo' ));
alert(jQuery.data( document.body ));
| Parameter | Description |
|---|---|
| element | Element type. The DOM object to store data on. |
| key | Optional. String type. The specified key name string. |
| value | Optional. Object type. Data of any type to be stored. |
More Examples
Retrieve data named "blah" stored on an element.
User Notes
Note: Since JavaScript is a weakly typed language, the type of the value retrieved by .data() will be automatically converted.
For example, there is a version module with a version tag of 1.0.
<div class="version" data-tag="1.0"></div>
Using the data() method, we hope to retrieve the version tag value as 1.0.
var version_tag = $('.version').data('tag') // The value retrieved by this expression is 1, not 1.0
But actually, $('.version').data('tag') retrieves the result as 1, not 1.0.
So how to retrieve the correct version number? Personally, I use the .attr() method.
var version_tag = $('.version').attr('data-tag') // The value retrieved by this expression is 1.0
In this way, it seems there is no need to use the data attribute.
YouTip