我正在尝试提醒用户选择的值指定的对象的键(NOT值),但我没有运气。如果我在for循环中手动输入对象名,我可以成功提醒键。下面是我的代码片段:
<select id="state" class="pure-input-1-2" onchange="populateAirport(this.value)">
<option value = ""></option>
<option value = "AL">AL</option>
<option value = "AK">AK</option>
</select>
function populateAirport(selectedValue){
AL = {"Birmingham–Shuttlesworth International Airport":"BHM","Huntsville International Airport":"HSV"}
AK = {"Ted Stevens Anchorage International Airport":"ANC","Fairbanks International Airport":"FAI","Juneau International Airport":"JNU","Ketchikan International Airport":"KTN"}
for(var i in selectedValue){//if I replaced 'selectedValue' with 'AL' I alert the keys in the object just fine
alert(i);
}
}
我只想成为一个基于所选值动态引用对象的人。在此先感谢您的帮助。
答案 0 :(得分:0)
在这种情况下,这就是我要做的事情:
HTML:
<select id="state" class="pure-input-1-2" onchange="populateAirport(this.value)">
<option value = ""></option>
<option value = "AL">AL</option>
<option value = "AK">AK</option>
</select>
<select id="airports"></select>
JS:
function populateAirport(selectedValue) {
$('#airports').empty();
var airports = {
"AL": {
"Birmingham–Shuttlesworth International Airport": "BHM",
"Huntsville International Airport": "HSV"
},
"AK": {
"Ted Stevens Anchorage International Airport": "ANC",
"Fairbanks International Airport": "FAI",
"Juneau International Airport": "JNU",
"Ketchikan International Airport": "KTN"
}
};
$.each(airports[selectedValue], function(key, val) {
var opt = "<option value='" + val + "'>" + key + "</option>";
$('#airports').append(opt);
});
}
Alternitavely,你的循环也可以是这样的:
for(var key in airports[selectedValue]){
var opt = "<option value='" + airports[selectedValue][key] + "'>" + key + "</option>";
$('#airports').append(opt);
}