开发者

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

开发者 https://www.devze.com 2023-02-17 08:56 出处:网络
Is there any benefit in using the data method when I can just store variables in plain javascript objects? It seems to me that using the jQuery data method is perform开发者_如何学JAVAance downgrade if

Is there any benefit in using the data method when I can just store variables in plain javascript objects? It seems to me that using the jQuery data method is perform开发者_如何学JAVAance downgrade if it means re-looking up the DOM element to retrieve the value of the key, if the DOM element has not been referenced prior?

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


It's simply a case of convenience and it depends on your implementation as to whether you would use the data functionality. You would normally use .data() when you wanted to store related values for a specific DOM element or, more likely, a "collection" of DOM elements. You would normally then retrieve those values as you iterate through the elements and make a decision or perform an action based on the value. Even if you are going to retrieve one value - if you cached the jQuery DOM element(s) it would be an inexpensive call to retrieve the attached value.


Because you cannot easily store data related to a certain DOM element using "plain javascript objects". If your data is not related to a certain DOM object you shouldn't use $.data of course!


I figured.

The DOM element can and should be referenced prior when using data, and that wouldn't result in a performance hit thus (and we still maintain the DOM_Element-key-value relationship).

So the initial look up for 'body' when storing the key-value is the only performance cost, and subsequent data retrievals don't have to find 'body' again:

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

精彩评论

暂无评论...
验证码 换一张
取 消