Reputation: 1305
I'm currently trying to use the .data() method to store data using a variable. 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! Thanks!
Upvotes: 0
Views: 861
Reputation: 84190
This is because in the second version, you are referencing the key "option" instead of the variable option (key "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 );
Upvotes: 3
Reputation: 146360
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));
Upvotes: 0
Reputation: 39689
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). If you want to be able to use a variable key, you'll need to use a temporary object. E.g.,
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));
Upvotes: 1
Reputation: 143037
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.
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));
Upvotes: 0
Reputation: 25796
You want to access the property... like this..
$(this).data({ option : 20 });
alert($(this).data('option'));
Upvotes: 2