使用jQuery的数据存储区与expando属性 [英] Using jQuery's datastore vs. expando properties
问题描述
我正在使用jQuery开发代码,需要存储与某些DOM元素相关的数据。关于使用html元素存储任意数据的如何还有很多其他问题,但我更感兴趣的是为什么我会选择一个选项而不是另一个。
I'm developing code using jQuery and need to store data associated with certain DOM elements. There are a bunch of other questions about how to store arbitrary data with an html element, but I'm more interested in why I would pick one option over the other.
为了极其简化的参数,我想要存储一个lineNumber属性,其中每一行都是有趣的表。
Say, for the sake of extremely simplified argument, that I want to store a "lineNumber" property with each row in a table that is "interesting".
选项1只是在每个DOM元素上设置一个expando属性(我希望我正确使用'expando'一词):
Option 1 would be to just set an expando property on each DOM element (I hope I'm using the term 'expando' correctly):
$('.interesting-line').each(function(i) { this.lineNumber = i; });
选项2将使用jQuery的data()函数将属性与元素关联:
Option 2 would be to use jQuery's data() function to associate a property with the element:
$('.interesting-line').each(function(i) { $(this).data('lineNumber', i); });
忽略我的示例代码的任何其他缺点,是否有充分理由选择一种存储方式属性超过另一个?
Ignoring any other shortcomings of my sample code, are there strong reasons why you would choose one means of storing properties over the other?
推荐答案
如果您正在创作插件,则应使用 $。data
。如果你需要经常存储属性而很少需要查询它,那么使用 $。data
。
If you are authoring a plugin you should use $.data
. If you need to store the attribute often and rarely need to query the DOM for it then use $.data
.
对于我所有的客户端应用程序,我倾向于在DOM元素本身上存储自定义DOM属性,以便稍后我可以使用属性 [] $ c查询它们$ c>选择器:
var domElement = $('.interesting-line[lineNumber=' + lineNumber + ']').get(0);
这比迭代调用 .data()的包装集更具可读性
每个项目。我经常与另一个在DOM元素上运行的第三方库进行交互,因此通过这种机制可以快速方便地访问DOM元素,使代码可以读取。
This is much more readable than iterating the wrapped set calling .data()
on each item. Often I am inter-oping with another 3rd party library that operates on a DOM element so having quick and easy access to the DOM element via this mechanism keeps the code readable.
它就像存储一个将 lineNumbers
映射到元素的查找表一样容易,但是相比之下,expando属性技术更不容易泄漏内存,因为你没有存储对DOM的引用您需要稍后清理的元素。
It's as easy as storing a lookup table mapping lineNumbers
to elements, however the expando attribute technique is less at-risk of leaking memory in comparison, since you are not storing references to DOM elements that you need to cleanup later.
5年后更新
只需在收到[当之无愧的] downvote后阅读此内容:请忽略上面的标记文字。 jQuery基于expando属性集不查询DOM,并且暂时没有这样做。所以使用 $。data
。当没有实用的方法时,没有理由污染DOM。
Update 5 years later
Just read this after it received a [well deserved] downvote: please ignore the striked text above. jQuery does not query the DOM based on expando properties set, and hasn't done so for a while. So use $.data
. There's no reason to pollute the DOM when there is no pragmatic use to do so.
这篇关于使用jQuery的数据存储区与expando属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!