1 <!DOCTYPE html> 2 3 <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 4 <head> 5 <meta charset="utf-8" /> 6 <title></title> 7 </head> 8 <body> 9 <style type="text/css"> 10 .cascade { float: left; width: 120px; height: 30px; } 11 .cascade select { width: 100%; height: 100%; } 12 </style> 13 14 <div class="cascade"> 15 <select id="province" onchange="change();"> 16 <option>--請選擇省份--</option> 17 </select> 18 </div> 19 20 <div class="cascade"> 21 <select id="city"> 22 <option>--請選擇市--</option> 23 </select> 24 </div> 25 26 <script type="text/javascript"> 27 //首先建立一個你需要省,和它對應的市的數組,如下: 28 var cityList = new Array(); 29 cityList['北京市'] = ['朝陽區', '東城區', '西城區', '海淀區', '宣武區', '豐台區', '懷柔', '延慶', '房山']; 30 cityList['上海市'] = ['寶山區', '長寧區', '豐賢區', '虹口區', '黃浦區', '青浦區', '南匯區', '徐匯區', '盧灣區']; 31 cityList['廣州省'] = ['廣州市', '惠州市', '汕頭市', '珠海市', '佛山市', '中山市', '東莞市']; 32 cityList['深圳市'] = ['福田區', '羅湖區', '鹽田區', '寶安區', '龍崗區', '南山區', '深圳周邊']; 33 cityList['重慶市'] = ['俞中區', '南岸區', '江北區', '沙坪壩區', '九龍坡區', '渝北區', '大渡口區', '北碚區']; 34 cityList['天津市'] = ['和平區', '河西區', '南開區', '河北區', '河東區', '紅橋區', '塘古區', '開發區']; 35 cityList['江蘇省'] = ['南京市', '蘇州市', '無錫市']; 36 cityList['浙江省'] = ['杭州市', '寧波市', '溫州市']; 37 cityList['四川省'] = ['四川省', '成都市']; 38 cityList['海南省'] = ['海口市']; 39 cityList['福建省'] = ['福州市', '廈門市', '泉州市', '漳州市']; 40 cityList['山東省'] = ['濟南市', '青島市', '煙台市']; 41 cityList['江西省'] = ['江西省', '南昌市']; 42 cityList['廣西省'] = ['柳州市', '南寧市']; 43 cityList['安徽省'] = ['安徽省', '合肥市']; 44 cityList['河北省'] = ['邯鄲市', '石家庄市']; 45 cityList['河南省'] = ['鄭州市', '洛陽市']; 46 cityList['湖北省'] = ['武漢市', '宜昌市']; 47 cityList['湖南省'] = ['湖南省', '長沙市']; 48 cityList['陝西省'] = ['陝西省', '西安市']; 49 cityList['山西省'] = ['山西省', '太原市']; 50 cityList['黑龍江省'] = ['黑龍江省', '哈爾濱市']; 51 cityList['其他'] = ['其他']; 52 53 /**科普小知識 54 *Option(text,value) 返回包含下拉列表框中的所有選項的一個數組,text==選項文本值;value==文本值 55 *add(new,old) 用於向<select>中添加一個<option>標簽, 56 new表示新添加到old之前的Option對象, 57 如果old為null,那則直接添加到<select>所有選項的末尾 58 *for(in) 循環遍歷對象的屬性 ,例:for(var i in cityList) 59 這里的i==cityList的屬性,就是省份名稱 60 例:for (var j in city[i]) 61 這里的j==cityList[i]的屬性,cityList中下表為i的屬性的屬性,就是每個城市的index(下標) 62 **/ 63 64 //然后寫一個方法把這一大長串的數組給他調到你需要的地方去 65 function change() { 66 var pVal = document.getElementById("province").value; //獲取省份列表中的值 67 var c = document.getElementById("city"); //獲取城市列表 68 c.options.length = 0; //清楚當前城市列表中的值 69 for (var i in cityList) { //循環遍歷cityList的屬性 70 if (i == pVal) { //判斷當i等於省份列表中的值時; 71 for (var j in cityList[i]) { //循環遍歷cityList[i]的屬性 72 c.add(new Option(cityList[i][j], cityList[i][j]), null) 73 //城市列表的末尾增加一個<option>選項,text:cityList[i][j],value:cityList[i][j] 74 } 75 break; 76 } 77 } 78 } 79 80 function allCity() { 81 var p = document.getElementById("province"); //獲取省份列表 82 for (var i in cityList) { //循環遍歷cityList的屬性 83 p.add(new Option(i, i), null); 84 //省份列表的末尾增加一個<option>選項,text:i,value:i 85 } 86 } 87 window.onload = allCity; 88 89 90 </script> 91 92 93 94 95 </body> 96 </html>
