简体   繁体   English

如何使用对象设置jQuery.data()

[英]How to set jQuery.data() using object

I'm currently trying to use the .data() method to store data using a variable. 我目前正在尝试使用.data()方法来使用变量存储数据。 However, for some reason it isn't working. 但是,由于某种原因,它无法正常工作。 Here is my proof of concept code: 这是我的概念证明代码:

var option = 'x';
$(this).data({ 'x' : 0 });
alert($(this).data(option));
$(this).data({ option : 20 });
alert($(this).data(option));

Surprisingly both of the alerts return 0 as opposed to 0 and then 20. Any help is really appreciated! 令人惊讶的是,这两个警报都返回0,而不是0,然后返回20。我们非常感谢您的帮助! Thanks! 谢谢!

This is because in the second version, you are referencing the key "option" instead of the variable option (key "x"). 这是因为在第二个版本中,您引用的是键“选项”,而不是变量选项(键“ x”)。

var option = 'x';
$(this).data({ 'x' : 7 });
console.log($(this).data(option));
$(this).data({ option : 20 });
console.log($(this).data('option'));

A simpler version of this: 一个更简单的版本:

option = 'x';
console.log({option: 20});

Outputs: 输出:

Object { option=20 }

You can however use the key value syntax with a variable. 但是,您可以将键值语法与变量一起使用。

$(this).data(option, 20 );

You want to access the property... like this.. 您想访问该属性。

$(this).data({ option : 20 });
alert($(this).data('option'));

The problem is that your option keyword in your object literal is being interpreted as a literal string for the key, rather than x (this is just how object literals work). 问题在于,对象文字中的option关键字被解释为键的文字字符串,而不是x (这就是对象文字的工作方式)。 If you want to be able to use a variable key, you'll need to use a temporary object. 如果要使用可变键,则需要使用一个临时对象。 Eg, 例如,

var option = 'x';
$(this).data({ 'x' : 0 });
alert($(this).data(option));
// create a data object so you can use a variable for the key
var obj = {};
obj[option] = 20;
$(this).data(obj);
alert($(this).data(option));

The reason is that your second one 原因是你的第二个

$(this).data({ option : 20 }); 

sets 20 to the option property, when you are actually meaning to set it to the x property. 实际将其设置为x属性时,将20设置为option属性。

I think this is what you are wanting to do instead: 我认为这是您要执行的操作:

var option = 'x'; 
$(this).data({ x : 0 }); 
alert($(this).data(option)); 
$(this).data({ x : 20 }); 
alert($(this).data(option)); 

Alternatively, you can instead use the key value syntax like this: 或者,您可以改为使用键值语法,如下所示:

var option = 'x'; 
$(this).data(option, 0); 
alert($(this).data(option)); 
$(this).data(option, 20); 
alert($(this).data(option)); 

The key to the data object cannot be a variable. 数据对象的键不能是变量。

What you can do is: 您可以做的是:

var option = 'x';
var data = {};
data['x'] = '0';
$(this).data(data);
alert($(this).data(option));

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

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