Home  >  Article  >  Web Front-end  >  Analysis of misunderstandings about the data method in jQuery_jquery

Analysis of misunderstandings about the data method in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:43:581022browse

When Brother Xie Liang and I were discussing something today, we talked about performance. He used attr to operate the custom attribute data-uid. I said that it is better to use data because it is implemented by dataset, and then he went to look at jQuery. The source code told me that this thing was not found, so I was puzzled. So I went to carefully read the source code of the data method, only to find that I had misunderstood it all along. Again, I would like to apologize to the group of friends who asked me about the data method before. I "lied" you, so come and hit me.

Today I will re-explain the data method. First, let’s take a look at what is said in the jQuery 1.11.0 manual. Please go to http://shouce.jb51.net/jquery/data.html ,
The usage is very clear here, but how is it implemented internally? Click me to see the source code (It doesn’t matter if you don’t understand, I will briefly analyze his process)

其实是这样的,当我们执行例如这样的语句时 $("#id").data("test"); (简化后的过程) 
第一步: jQuery 会获取到 $("#id") 元素,对吧、 
第二步: 执行到 data方法 的时候,他会通过 attributes 取我们要的对应值。 
第三步: 返回结果给我们,然后 jQuery 把值缓存到内部对象里 
第一次取的时候,我们可以得到的 undefined,字符串,数字或者解析后的json。 
 
那有人会说这个和 attr 有什么区别呢? 
当我们第二次执行 $("#id").data("test"); 的时候: 
第一步: jQuery 会获取到 $("#id") 元素,和上面一样。 
第二步: 执行到 data方法 的时候,从 jQuery 的缓存中取值 
第三步: 返回结果给我们 
 
发现第二步不同了,对吧,为什么不是从 attributes 取值,而是从缓存中取呢? 
缓存其实是js的对象,简单说就类似 var cache = {}; jQuery 在第一次取值之后就会保存到这个缓存对象中,这样我们再次操作的时候就非常快了、 
往往性能的损耗都是在 dom 操作上,所以避免重复操作 dom 是非常必要的。 
 
到这,也能看出他和 attr 最大的区别了,比如 <div id="id" data-test="hehe"></div> 
$("#id").data("test", "123"); 执行后依然是 data-test="hehe"
$("#id").attr("data-test", "123"); 执行后会是 data-test="123"
 
那么我们要给一个元素赋值值,或者对象的时候他们有什么区别呢?比如 <div id="id" data-test="hehe"></div> 
$("#id").data("test", {str: "hehe"}); 会把 {str: "hehe"} 赋值给 缓存,元素节点上依然是 data-test="hehe"
$("#id").attr("data-test", {str: "hehe"}); 执行后会是 data-test="[object Object]"
这个应该也有不少人遇到,至少群里有不少人问过这个问题。

Actually, I didn’t lie to you before. There is no need to always use attr for custom attributes. Data is a Swiss Army knife given to us by jQuery, which is very sharp.

Okay, I am lazy and I am too lazy to illustrate pictures. I have already written a lot of words. If there is anything I say that is wrong, please hit me up

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn