0

我正在尝试为城市和(相关)州创建相关的下拉列表。这是 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]);
    }
}

当我尝试选择选项时,先前选择的州的城市出现在第二个下拉框中。如何避免这种情况?

4

1 回答 1

1

因为您尚未从“state_id”元素中删除之前添加的城市。因此,在获取状态元素的 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
于 2013-11-03T08:02:01.603 回答