Why use jQuery data to store variables instead of regular JavaScript objects?

Is there any use in using the method when I can just store variables in simple javascript objects? It seems to me that using the jQuery data method is a performance hit if it means re-viewing the DOM element to retrieve the key value, if the DOM element has not previously been referenced?

Sorry if this is painfully obvious to javascript developers, but I hope to fully understand this.

+3
source share
3 answers

This is just a case of convenience, and it depends on your implementation as to whether you will use the functionality of the data. Normally, you should use .data () when you want to save related values ​​for a specific DOM element or, more likely, a "collection" of DOM elements. Typically, you extract these values ​​when repeating elements and make a decision or perform an action based on the value. Even if you are going to get one value - if you were caching DQ elements of jQuery, it would be an inexpensive call to get an attached value.

+3
source

, DOM, " javascript". DOM, $.data, !

+1

I thought.

The DOM element may also refer to earlier when using the data, and this would not lead to a result (thus, we retain the DOM_Element-key-value relation).

Thus, the initial search for the “body” while storing the key value is the only performance, and subsequent data retrievals should not search for the “body” again:

b = $('body');
b.data('key', 'value');
alert(b.data('key'));
0
source

All Articles