我有一个数据集为
var data1 = {values:[
{ X: "33", Y: 12 },
....
]};
var data2 = { values:[
{ X: "Jan", Y: 2 },
...
]};
我想加载适当的数据集
$(document).ready(function() {
$(".test").click(function(){
var data = $(this).val() // the value will be data1 or data2
// how can I make the data a JSON equal to data1 or data2 instead of
// assigning the static value of $(this).val() to it.
}
});
如何从静态值创建 var data
?
最佳答案
不要。
将data1
、data2
作为对象的属性,并使用方括号成员运算符访问它们。
var dataset = {
data1: {
values: [{
X: "33",
Y: 12
}, ....]
}
data2: {
values: [{
X: "Jan",
Y: 2
}, ...]
};
}
var data = dataset[$(this).val()]
虽然如果您的 data1
和 data2
是全局变量,您可以从 window
对象以相同的方式访问它们。
var data = window[$(this).val()]
但是像 dataset
这样的对象仍然比一堆全局变量更好。
关于javascript - 如何在 jQuery 中通过字符串值调用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10669782/