创建对jQuery.data键的本地引用 [英] Creating a local reference to a jQuery.data key
问题描述
我正在对jQuery.data()
进行一些测试,并且试图创建对某个数据键的本地引用,我希望可以对该数据键进行本地更改,并且仍然会影响外部".我想举个例子会更好,因为我将半长代码发布在jsFiddle而不是这里:
I'm doing some testing on jQuery.data()
, and I'm trying to create a local reference to a certain data-key, which I hopefully can change locally and still affect "outside". I think it would be better with an example, due to the semi-long code I posted it on jsFiddle instead of here:
http://jsfiddle.net/esbenp/p4kt2/22/
我希望的输出是:
{1: {length: 1}, total: 1}
但局部变量仅会影响length属性:
but only the length property is affected by incrementing the local variable:
{1: {length: 1}, total: 0}
我该怎么办?
推荐答案
如果将对象(或数组)存储在.data()
中,则实际上是在存储引用,如果您这样做:
If you store an object (or array) in .data()
then you're actually storing a reference to it, so if you do:
var obj = { key: 'value' }
$(el).data('obj') = obj;
obj.key = 'new value';
$(el).data('obj').key
也将是new value
,因为它是同一对象.
但是,如果存储的值不是普通类型(例如数字或字符串),则会存储其副本:
However if the value stored is a plain type instead (e.g. a number or a string) that a copy of it will be stored:
var n = 5;
$(el).data('obj') = n;
n++;
$(el).data('obj')
仍为5.
这篇关于创建对jQuery.data键的本地引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!