jQuery:在jQuery对象中存储其他/额外的数据/信息吗? [英] jQuery: Store additional/extra data/info inside a jQuery object?
问题描述
在jQuery对象中存储额外的数据是否可能并且很聪明?
Is it possible and smart to store extra data inside a jQuery object?
现在,我有一些包含某些数据的对象,但是这些对象也具有该数据的可视表示.这可行,但是我有很多代码可以使它们保持同步.
Right now I have objects that contain some data but these objects also have a visual representation of that data. This works but I have a lot of code to keep them both in sync.
例如,如果您从dom中删除一个对象,我还必须从对象数组中删除相关的对象.删除是相当简单的,但是如果我开始对对象进行排序/移动,它会变得更加复杂.
For example if you delete an object from the dom I also have to delete the related object from the object array. Deleting is fairly simple but it gets a little more complicated if I start sorting/moving the objects around.
推荐答案
您可以使用 $.data()
为此:)
You can use $.data()
for this :)
例如:
$.data(element, 'varName', value); //store
var value = $.data(element, 'varName'); //get
或使用对象方法 .data()
:
Or use the object method .data()
:
$("#ElementID").data('varName', value); //store
var value = $("#ElementID").data('varName'); //get
这不会在对象上存储数据,而是将其存储在$.cache
中(在此页面上的控制台中尝试),但是它通过
This doesn't store the data on the object, rather it stores it in $.cache
(try it in your console on this page), but it's associated with the object, via this[$.expando]
.
但是,如果您调用 .empty()
来删除对象,或者 .removeData()
或
However if you call .empty()
that removes an object, or .remove()
, it'll do the cleanup for you. You can also call .removeData()
or $.removeData()
to remove it directly.
这篇关于jQuery:在jQuery对象中存储其他/额外的数据/信息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!