Jquery data() storage

只谈情不闲聊 提交于 2019-12-17 20:09:01

问题


Can any one tell me where jquery data() stores the data and when it is get erased and how?

Is there any performance issue if I use this to store ajax call result?

For example:

$("body").data("test", { myData: 'abcd'});

回答1:


see the content from jquery

The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page. We can set several distinct values for a single element and retrieve them later:




回答2:


All data is stored inside a property of the jQuery object named cache. Log the contents of $.cache in your console to see all data and events associated with any DOM element.

The way jQuery links up a DOM object with an object in this cache is by manipulating the DOM object. Say we have a input element

<input type="text" value="hello" />

which has a data key named "foo"

$(e).data("foo", "bar");

Now jQuery maintains a random string of the form jQuery<current time in ms>, for example, jQuery1291790929680, which is also accessible by $.expando. jQuery adds this expando string as a key to each DOM object that has an associated data item or event. So the DOM object for the above input element will contain this expando key with some integer value such as:

jQuery1291790929680: 4

4 is just a random example, but this number denotes an index in the $.cache object, where the associated data and events for this DOM object are stored. So given this information, to retrieve the data of the above input element, we can indirectly write:

$.cache[4]["foo"]

which should return "bar", which is an indirect way of writing $(e).data("foo").

An illustrated example of the above nonsense :)



来源:https://stackoverflow.com/questions/4384784/jquery-data-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!