我有一张美国地图,其中所有50个州都是可点击的按钮,当用户点击我要显示有关该状态的信息的状态时,动态调用该状态的数组。以下是我自己的弱尝试,显然不起作用。
var stateList = new Array("AK","AL","AR","AZ","CA","CO","CT","DC","DC2","DE","FL","GA","GU","HI","IA","ID",
"IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY",
"OH","OK","OR","PA","PR","RI","SC","SD","TN","TX","UT","VA","VT","WA","WI","WV","WY");
function listenerForI( i ) {
document.getElementById(stateList[i])
.addEventListener('mousedown', function() {
stateSelect(stateList[i]);
}, false);
}
for (var i = 0; i < stateList.length; i++) {
listenerForI( i );
}
var HIdat = new Array(20,28,50,2) //one array for all 50 states COdat, AKdat, etc.
function stateSelect(state){
var display_data1 = state + "dat[0]";
alert(display_data1);
}
我应该使用eval()吗?我听说过你可以用全局“窗口[]”做些什么,但我不明白这是怎么回事。
答案 0 :(得分:6)
您应该将状态数组存储在它们自己的对象中:
var stateData = {
HI: [1, 2, 3],
IL: [4, 5, 6],
...
};
var myData = stateData[state];
答案 1 :(得分:0)
使用window
是一个选项,如下所示:
window[state + "dat"]
会为您提供数组。
但我建议......正是SLaks发布的内容,所以请改为。
答案 2 :(得分:0)
在JavaScript中,全局变量是窗口对象的成员,因此您可以使用数组索引语法来获取它们而不使用eval
,这通常是要避免的,如下所示:
function stateSelect(state) {
var display_data1 = window[state + "dat"];
alert(display_data1);
}