我正在尝试为城市和(相关)状态创建相关的下拉菜单。 这是state.html
<html>
<head><script type= "text/javascript" src = "countries2.js"></script></head>
<body>
Select Country: <select onchange="print_state('state',this.selectedIndex);" id="country" name ="country"></select>
<br />
City/District/State: <select name ="state" id ="state"></select>
<script language="javascript">print_country("country");</script>
</body>
</html>
和states.js
var country_arr = new Array("Andaman & Nicobar ","Andhra pradesh","Arunachal Pradesh","maharashtra");
var s_a = new Array();
s_a[0]="";
s_a[1]="Nicobar|North and Middle Andaman|South Andaman";
s_a[2]=" Adilabad|Anantapur|Chittoor|East Godavari|Guntur|Hyderabad|Kadapa|Karimnagar|Khammam|Krishna|Kurnool|Mahabubnagar|Medak|Nalgonda|Nellore|Nizamabad|Prakasam|Rangareddy|Srikakulam|Visakhapatnam|Vizianagaram|Warangal|West Godavari";
s_a[3]="Anjaw|Changlang|Dibang Valley|East Kameng|East Siang|Kurung Kumey|Lohit|Lower Dibang Valley|Lower Subansiri|Papum Pare|Tawang|Tirap|Upper Siang|Upper Subansiri|West Kameng|West Siang";
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
var x, i=0;
for(x in country_arr){
option_str.options[i++] = new Option(country_arr[x],country_arr[x]);
}
}
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
var x, i=0; state_index++;
var state_arr = s_a[state_index].split("|");
for(x in state_arr){
option_str.options[i++] = new Option(state_arr[x],state_arr[x]);
}
}
当我尝试选择选项时,先前选择状态的城市会显示在第二个下拉框中。怎么避免这个??
答案 0 :(得分:1)
因为您尚未从“state_id”元素中删除以前添加的城市。因此,在获取state元素的id后,在print_state函数中删除其所有子元素,然后继续。您可以应用许多方法从DOM节点中删除子元素。其中一种纯粹的javascript方式如下:
while(option_str.hasChildNodes()){
option_str.removeChild(option_str.lastChild);
}
如果你可以在你的情况下使用它,那么更简单的一个衬里方法将使用innerHTML属性:
option_str.innerHTML = ""; //will remove everything including the childs from the DOM node