jquery data()

data()

.data( key, value )

  Description: Store arbitrary data associated with the matched elements.

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

.data( key )

  Description: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.

  • .data( key )
  • .data()

Example1

$( "body" ).data( "foo", 52 ); 
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data();
// { foo: 52, bar: { myType: "test", count: 40 }, baz: [ 1, 2, 3 ] }

Example2

HTML5 data-* Attributes

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

Additional:

jQuery searches among the attributes of the element, converting a camel-cased string into a dashed string and then prepending data- to the result. So, the string lastValue is converted to data-last-value.

原文地址:https://www.cnblogs.com/hzj680539/p/5031327.html