简体   繁体   English

jQuery如何将domElement哈希与data()一起使用?

[英]How does jQuery hash domElements to use with data()?

The sorcecode for jQuery is a little bit confusing to me, with a lot of global variables and cross-references. jQuery的sorcecode有点令人困惑,因为它具有许多全局变量和交叉引用。

I have several assumptions as to how jQuery.data() works: It creates a hashtable and hashes a domElement as a key, and sets the data as a value. 关于jQuery.data()工作方式,我有几个假设:它创建一个哈希表,并将domElement哈希为键,并将数据设置为值。 I got to this conclusion since there is no changes to the dom, so somehow hashing the domElement is the only possible thing left. 我得出这个结论是因为dom没有任何变化,因此以某种方式对domElement进行散列是剩下的唯一可能的事情。

Question 1: How is it hashed? 问题1: 如何进行哈希处理?

Question 2: Is it possible to extend the hashing algorithm to work persistently with saved elements in the localStorage? 问题2: 是否可以扩展散列算法,使其与localStorage中保存的元素持久地协同工作?

It is stored in the $.cache variable. 它存储在$.cache变量中。 You can see it if you for example open your browser console and type it. 例如,如果您打开浏览器控制台并键入,就可以看到它。

Here is an example 这是一个例子

 $('div').data('tryme', 'okay'); $('p').data('try', 'okay'); $('div').append(JSON.stringify($.cache)); console.log($('div'), $('p')) 
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div></div> <p></p> 

How it works 这个怎么运作

Each time you call $(domElement) jQuery will assign a key to it starting with 1 . 每次您调用$(domElement) jQuery都会为其分配一个键,从1开始。 You can think of it as an ID. 您可以将其视为ID。 As you can see in the result above each object with the data is assigned to a key. 您可以在上面的结果中看到,每个带有数据的对象都分配给一个键。

When you call $('div').data() , jQuery will just get the key for that element and get the resulting data from the $.cache variable. 当您调用$('div').data() ,jQuery将仅获取该元素的键并从$.cache变量获取结果数据。 You can check the keys doing something like 您可以检查按键,例如

 $('div').each(function(){ $(this).data(this.className, $(this).attr('data-class')); }); $('div').each(function(){ $('<div/>', { text: 'I am ' + this.className + ', my key is ' + this[$.expando] + ' and my data is ' + JSON.stringify($.cache[this[$.expando]].data) }).appendTo('span'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class='ok1' data-class='test1'></div> <div class='ok2' data-class='test2'></div> <div class='ok3' data-class='test3'></div> <div class='ok4' data-class='test4'></div> <span> </span> 

With the result of this data you can simple save it in localStorage or do whatever you want. 利用这些数据的结果,您可以简单地将其保存在localStorage中或执行任何所需的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM