jQuery .data()如何工作的问题 [英] JQuery .data() how to work question
问题描述
我对.data()有疑问.在stackoverflow答案中,jquery将数据保存在缓存对象中,在缓存对象中以dom元素的哈希作为后缀.例如,将元素视为:
I have a question about .data(). In a stackoverflow answer, jquery saves data in cache object where cache index is suffixed with a hash of the dom element. For example, consider an element as:
- #result ID,
- 在Jquery缓存的第3个索引中
- 并带有一个键:"carModel"&&值:奥迪"
现在,我阅读了.data()将键值与结果ID的哈希值和缓存索引一起保存.现在我的问题是,jQuery如何哈希dom中的任意元素?
Now, I read .data() will save the key-value with a hash value of result ID and cache index. Now my question is how jquery hash an arbitrary element in dom?
例如,考虑以下html:
For example, consider the following html:
<div id="begin">
<p id="hello">Hello World</p>
<p id="another">another</p>
<div> <p>
test p
</p>
</div>
<p id="last">last</p>
<div>
为每个值分配一个值的代码:
Code to assign a value to each:
var i=0;
$("p").each( function() {
$(this).data("value",i);
++i;
});
最后,让我们检索最里面的p元素的值:
Lastly, let's retrieve inner most p element's value:
alert( $("div div p").data("value") );
// output correctly => 2
我想知道它是如何工作的? :-)我的意思是说,jquery如何对元素进行哈希处理,从而可以在没有明确标识符(例如element-ID)的情况下检索它们?
I want to know how this works? :-) I mean how jquery hashed elements in such a way where they can be retrieved without definite identifier (like element-ID) to them?
感谢您的帮助...
推荐答案
jQuery数据的工作方式是将内部的所有数据存储在名为cache
的变量中.每个jQuery会话都会创建一个扩展",基本上是一个随机字符串,如jquery161362319162
特定于该会话.将其放置在DOM中的每个对象(例如element.jquery161362319162)上,并在缓存中添加索引的值.
The way in which jQuery data works is by storing all the data internal in a variable called cache
. Each jQuery session creates a "expando" which is basically a random string like jquery161362319162
specific to that session. This is placed on each object in the DOM such as element.jquery161362319162 with a value of the index in cache.
这是一个大致的工作原理示例.要在一个元素上添加对多个数据的支持,还需要做更多的工作,但是您将了解它在内部如何工作.
Here is a very basic example of roughly how it works. This will need a bit more work to add support for multiple data on an element, but you'll get the idea of how it works internally.
var cache = []; // Stores all the data for each element
var uid = 'jquery89437507043'; // random generated id,
// jQuery uses a function to automatically
// generate such a value
function data(element, key, data)
{
if (data !== undefined) // We are setting data
{
var thisCache[key] = data;
cache.push(thisCache)
element[uid] = cache.length; // Place the index cache
// for this data set on the element
}
else
{
return cache[element[uid]][key];
}
}
用法
var div = $('div').get(0);
data(div, 'test', { 'apple': 'juice' });
alert(data(div, 'test').apple); // Will alert 'juice'
这篇关于jQuery .data()如何工作的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!