4

Let's say I have to remember the initial height of certain element. A common practice I see is to save this value with $.data on that element.

I fail to understand the benefits of this. Why not simply keep a simple variable with that value, or an array with values if there are multiple elements? Keeps the code easy to understand.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
thelolcat
  • 10,995
  • 21
  • 60
  • 102
  • Association with the node, most likely. However, I'll leave it to those who are more expert than me to answer this one fully. – esqew Jul 01 '14 at 16:03
  • 1
    If you want to associate it with the element? – SLaks Jul 01 '14 at 16:04
  • Related : **[Advantages of .data()](http://stackoverflow.com/q/12801464/3639582)** – Shaunak D Jul 01 '14 at 16:04
  • Association with the node, definitely plus clean. If you have 100 such elements, its unclean maintaining 100 variables, plus extra associative info to map the nodes to those variables. – techfoobar Jul 01 '14 at 16:04

3 Answers3

6

The main reason for using data() is to store data specific to a certain element so it can be accessed later, here's an example

$('.elements').on('click', function() {
     $(this).data('value', this.value);
});

$('.elements').on('keyup', function() {
    $(this).val( $(this).data('value') );
});

Note that the event handler could match a number of different elements, and using data() keeps the data associated to each element without using several variables for each element or a complex array.

EXAMPLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
4

It allows the function to be reused to apply the same effect to other elements (without having to deal with closures).

It allows the value to be initialized with HTML.

It makes it easier for developer tools to inspect the data.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Basically because le you save information INSIDE A NODE, preventing possible variable name conflicts and without the need to pass variables around. All the needed informations about a node, stay with the node itself

RiccardoC
  • 876
  • 5
  • 10