jQuery如何使用.data()存储数据? [英] How does jQuery store data with .data()?

查看:410
本文介绍了jQuery如何使用.data()存储数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑jQuery如何使用 .data()函数存储数据。

I am a little confused how jQuery stores data with .data() functions.

这是什么叫 expando
或者这是使用HTML5网络存储,虽然我认为这不太可能?

Is this something called expando? Or is this using HTML5 Web Storage although I think this is very unlikely?

文档说:


.data()方法允许我们以一种不受循环引用和内存泄漏的方式将任何类型的数据附加到DOM元素。

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

当我读到有关expando的消息时,它似乎存在内存泄漏的风险。不幸的是,我的技能还不足以阅读和理解jQuery代码本身,但我想知道jQuery如何使用 data()来存储这些数据。

As I read about expando, it seems to have a risk of memory leak. Unfortunately my skills are not enough to read and understand jQuery code itself, but I want to know how jQuery stores such data by using data().

  • http://api.jquery.com/data/

推荐答案

基本上jQuery使用<$保存您存储/检索的信息c $ c>数据(名称,值)/数据(名称)并在名为<$的内部javascript对象中使用 removeData(name)删除C $ C>缓存。其余的只是一些javascript魔术,使其工作并保持所有关联正确。

Basically jQuery holds the information you store/retrieve with data(name, value)/data(name) and remove with removeData(name) in an internal javascript object named cache. The rest is just a bit of javascript magic to make it work and keep all the associations right.

哦,并回答你问题的第一部分。它既不是expando也不是HTML5 WebStorage。

Oh and to answer the first part of your question. Neither is it expando nor HTML5 WebStorage.

为了纠正自己,我认为jQuery确实在一次使用expando。它为您使用 data()打开的元素设置了一个属性,以便向它们存储信息。属性名称如下所示

To correct myself I think jQuery does use expando in one occasion. It sets one attribute on those elements you used data() on to store information to them. The attribute name looks like this

"jQuery" + now() //e.g. jQuery1268647073375

btw。 now()是一个内部函数,它返回(新日期).getTime()

btw. now() is an internal function which returns (new Date).getTime()

,值是由jQuery生成的 UUID

and the value is an UUID generated by jQuery.

这样jQuery以后on可以从它的内部缓存中检索正确的关联数据。

This way jQuery later on can retrieve the correct associated data from it's internal cache.

所以如果你关注IE中的expando,我记得你无法删除它们,那么泄漏应该是最小的,因为jQuery每个元素只使用1个expando存储数据。除非你在字面上1000个元素上调用 data(),否则我看不出内存问题

So if you are concerned about expando in IE, where I recall you can't delete them, then the leak should be minimal as jQuery only uses 1 expando per element you store data on. Unless you call data() on literally 1000s of elements I see no memory problems

这篇关于jQuery如何使用.data()存储数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆