jQuery Data

 

HTML5 adds data-*custom properties (data attributes), so that we can read and write data on any element, but does not affect the layout of the page.

For example, we can customize the data attribute like this:

<article
  id="electriccars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
  ...
</article>

jQuery also provides convenient functions to process the data bound to specific elements.

.data(key)

How to get the data on the element?

// HTML
<div data-role="page" data-last-value="43" data-hidden="true"></div>
// jQuery
$('div').data('role') === "page";
$('div').data('lastValue') === 43;
$('div').data('hidden') === true;
jQuery will automatically convert the string into the corresponding JavaScript value (like the number and boolean values ​​in the example above)

You can also use JSON syntax in data-* attributes

If the value of the data attribute is {or [beginning, jQuery will automatically help you to resolve when JSON into JavaScript Object / Array.

E.g

// HTML
<div data-options='{"name":"John"}'></div>
// jQuery
$('div').data('options').name === 'John';

.data(key, value)

In addition to using HTML data-* attributes, jQuery also allows us to bind arbitrary data to specific elements very flexibly.

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

$('#foo').data('foo'); // 52
/// You can also get all the data bound to the element at once
$('#foo').data(); // {foo: 52, bar: {myType: 'test', count: 40}, baz: [1, 2, 3]}

.removeData([name])

.removeData() can be used to remove the data bound to the element via jQuery. (But will not delete the data-* attributes on the HTML)

$('div').data('test1', 'VALUE-1');
$('div').data('test2', 'VALUE-2');

$('div').removeData('test1');
// Without specifying the key, it means deleting all the bound data on this element
$('div').removeData();

Post a Comment

0 Comments