我想根据之前选择的选项的值填充选择选项。
<label for="state" class="block">State:*</label>
<select name="state" id="state" tabindex="1">
<option value="Arizona">Arizona</option>
<option value="Arkansas">Arkansas</option>
<option value="Colorado">Colorado</option>
</select>
<label for="location" class="block">Preferred Location:*</label>
<select name="location" id="location" tabindex="2">
<option value=""></option>
</select>
多数民众赞成我的HTML。现在我有我的js,它有效,但我想知道是否有更好的方式。
var State = $('#state').val();
var Location = $('#location');
setOptions(State);
function setOptions(chosen){
var Location=document.myform.location;
Location.options.length=0;
var Arizona = {
0 : 'Select Location',
3 : 'Phoenix (Chandler)',
4 : 'Scottsdale',
5 : 'Tuscon'
};
var Arkansas = {
2 : 'Little Rock'
};
var Colorado = {
6 : 'Colorado Springs'
};
if(chosen=="Arizona"){
var myobject = Arizona;
}
if(chosen=="Arkansas"){
var myobject = Arkansas;
}
if(chosen=="Colorado"){
var myobject = Colorado;
}
for(index in myobject) {
Location.options[Location.options.length]=new Option(myobject[index], index);
}
有没有办法可以根据其他选择框告诉它使用哪个对象?
谢谢!
答案 0 :(得分:0)
使用嵌套对象:
var locations = {
Arizona: {
0 : 'Select Location',
3 : 'Phoenix (Chandler)',
4 : 'Scottsdale',
5 : 'Tuscon'
},
Arkansas: {
2 : 'Little Rock'
},
Colorado: {
6 : 'Colorado Springs'
}
};
var myobject = locations[chosen];
for(index in myobject) {
Location.options.push(new Option(myobject[index], index));
}