jQuery.data()Method

jQuery 杂项方法jQuery Miscellaneous Methods

Example

Store data on a div element first, then retrieve it

<div> The stored value is <span></span> and <span></span> </div> <script> $(function () { var div = $( "div" )[ 0 ]; jQuery.data( div, "test", { first: 16, last: "pizza!" }); $( "span:first" ).text( jQuery.data( div, "test" ).first ); $( "span:last" ).text( jQuery.data( div, "test" ).last ); }) </script>

Try it Yourself »

Definition and Usage

$.data() function is used to store and retrieve data on the specified element, and returns the set value.

Tip: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 currently does not provide cross-platform setting on XML documents. Internet Explorer does not allow attaching data to XML documents via custom attributes.


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 ));

Parameters Description
element Element type - The DOM object on which data is to be stored.
key Optional. String type - The specified key name string.
value Optional. Object type - Data of any type to be stored.


实例

More Examples

Retrieve Data
Retrieve the data named "blah" stored on the element.


jQuery 杂项方法jQuery Miscellaneous Methods

Other Extensions