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!
The problem is that your
optionkeyword in your object literal is being interpreted as a literal string for the key, rather thanx(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.,