我在Javascript中创建了相同的代码,当用户更改状态时,它会更改城市下拉列表中的选项。
代码的问题在于它不起作用。我认为代码没问题,但我是JavaScript的新手,所以我看不到错误。
请检查我的代码并查看我的错误。感谢。
JavaScript的:
function drzava_promjena() {
var obj_state = document.getElementById("id_drzava")
var index = obj_states.selectedIndex;
var value_state = obj_state.options[index].value;
towns = town_list[value_state];
var obj_town = document.getElementById("id_gradovi");
while (obj_town.options.length > 0) {
obj_town.remove(0);
}
var new_value;
for (var i = 0; i < towns.length; i++) {
new_value = document.createElement("option");
new_value.value = towns[i];
new_value.text = towns[i];
try {
obj_town.add(new_value);
} catch (e) {
obj_town.appendChild(new_value);
}
}
这是HTML:
<select id="id_drzava" onchange="drzava_promjena(this);">
<option value="Austrija">Austrija</option>
<option value="Njemacka">Njemacka</option>
<option value="Slovenija">Slovenija</option>
<option value="Ceska">Ceska</option>
</select>
<br>
<select id="id_gradovi" onchange="">
<option value="0"></option>
</select>
<br>
<select id="id_uni" onchange="">
<option></option>
</select>
答案 0 :(得分:0)
尝试以下代码。我还要put up a fiddle来演示。
JavaScript的:
var populateCities = function (country, target_id) {
var i = 0, options, cities, selection, target;
cities = {
"usa": {
"dallas": "dal",
"san francisco": "sf",
"houston": "hou"
},
"fr": {
"paris": "pr",
"la riche": "lr"
}
};
selection = country.options[country.selectedIndex].value;
target = document.getElementById(target_id);
target.options.length = 0;
if(selection !== 'none') {
options = cities[selection];
for(var city in options) {
target.options[i] = new Option(city, options[city]);
i++;
}
}
}
HTML:
<select id="country" onchange="populateCities(this, 'cities')">
<option selected value="none">Pick a country</option>
<option value="usa">USA</option>
<option value="fr">France</option>
</select>
<select id="cities"></select>