是首先應該添加兩個下拉列表並設置id屬性來方便操作:
1 <select id="country"> 2 <option>國家</option> 3 </select> 4 <select id="city"> 5 <option>城市</option> 6 </select>
js代碼中首先需要聲明國家和城市兩個數組:
var country = ['中國', '美國','英國']
var city = [
['北京', '上海'],
['紐約'],
['倫敦']
]
然后通過id獲取頁面中的下拉菜單元素:
var cou = document.getElementById("country");
var cit = document.getElementById("city");
然后初始化第一個列表:
//初始化國家下拉列表 for(var i = 0; i < country.length; i++) { //新的option var option = new Option() //賦值 option.appendChild(document.createTextNode(country[i])) //插入 cou.appendChild(option) }
在第一個下拉列表中選擇國家后,第二個列表顯示相應的城市:
//為國家下拉列表添加事件 cou.addEventListener('change', function(){ //另城市列表變為初始狀態,可以注釋掉查看效果 cit.options.length = 1; //如果國家選擇不為默認值 if(cou.selectedIndex != 0) { //遍歷相應國家的城市 for(var j = 0; j < city[cou.selectedIndex - 1].length; j++) { var option2 = new Option(city[cou.selectedIndex-1][j],city[cou.selectedIndex-1][j]) cit.options.add(option2) } } });

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <select id="country"> <option>國家</option> </select> <select id="city"> <option>城市</option> </select> <script> var country = ['中國', '美國','英國'] var city = [ ['北京', '上海'], ['紐約'], ['倫敦'] ] var cou = document.getElementById("country"); var cit = document.getElementById("city"); //初始化國家下拉列表 for(var i = 0; i < country.length; i++) { //新的option var option = new Option() //賦值 option.appendChild(document.createTextNode(country[i])) //插入 cou.appendChild(option) } //為國家下拉列表添加事件 cou.addEventListener('change', function(){ //另城市列表變為初始狀態,可以注釋掉查看效果 cit.options.length = 1; //如果國家選擇不為默認值 if(cou.selectedIndex != 0) { //遍歷相應國家的城市 for(var j = 0; j < city[cou.selectedIndex - 1].length; j++) { var option2 = new Option(city[cou.selectedIndex-1][j],city[cou.selectedIndex-1][j]) cit.options.add(option2) } } }); </script> </body> </html>