AJAX-簡單的省市縣三級聯動
阿新 • • 發佈:2017-06-11
rip cnblogs wid clas 指定 聯動 ajax func 分享
index.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>ajax省市縣三級聯動</title> 6 </head> 7 <body> 8 <select style="width: 102px;" id="pre" onchange="changeCity(this);"> 9 <option value=" ">--請選擇省--</option> 10 </select> 11 <select style="width: 102px;" id="city" onchange="changeArea(this)";> 12 <option value=" ">--請選擇市--</option> 13 </select> 14 <select style="width: 102px;" id="area"> 15 <option value=" ">--請選擇縣--</option> 16 </select> 17 </body> 18 <script> 19 var pres = ["北京", "吉林", "山東"]; 20 21 var cities = [ 22 ["東城", "昌平", "海澱"], 23 ["長春", "吉林"], 24 ["濟南", "青島"] 25 ]; 26 27 var areas = [ 28 [ 29 ["東城1", "東城2", "東城3"], 30 ["昌平1", "昌平2", "昌平3"], 31 ["海澱1", "海澱2", "海澱3"] 32 ], 33 [ 34 ["長春1", "長春2"], 35 ["吉林1", "吉林2", "吉林3"] 36 ], 37 [ 38 ["濟南1", "濟南2"], 39 ["青島1", "青島2"] 40 ] 41 ]; 42 //設置一個省的公共下標 43 var pIndex = -1; //-1表示未被選中的狀態 44 var preEle = document.getElementById("pre"); 45 var cityEle = document.getElementById("city"); 46 var areaEle = document.getElementById("area"); 47 //先設置省 48 for (var i = 0; i < pres.length; i++) { 49 //創建節點: pres[i]->表示文本、 i->表示value 50 var myOption = new Option(pres[i], i); 51 //將元素添加到指定的節點(preEle放到myOption處) 52 preEle.options.add(myOption); 53 } 54 function changeCity(obj) { 55 //先清空(如果不想讓cityEle、areaEle自動補全、則要將length=0->length=1) 56 cityEle.options.length = 0; 57 areaEle.options.length = 0; 58 //獲取值 59 var val = obj.value; 60 //window.alert(val); //值為:0->北京、 1->吉林、2->山東 61 pIndex = obj.value; //這裏先捆綁0、1、2 62 //獲取cities 63 var cs = cities[val]; 64 // window.alert(cs); //北京->東城,昌平,海澱 65 //獲取默認區 66 var as = areas[val][0]; 67 68 for (var i = 0; i < cs.length; i++) { 69 var myOption = new Option(cs[i], i); 70 cityEle.options.add(myOption); 71 } 72 for (var i = 0; i < as.length; i++) { 73 var myOption = new Option(as[i], i); 74 areaEle.options.add(myOption); 75 } 76 } 77 function changeArea(obj) { 78 var val = obj.value; 79 //window.alert(val); //吉林:0->長春、1->吉林 80 var as = areas[pIndex][val]; 81 //window.alert(pIndex); //這裏釋放0、1、2 82 //先清空 83 areaEle.options.length = 0; //(如果不想讓cityEle、areaEle自動補全、則要將length=0->length=1) 84 for (var i = 0; i < as.length; i++) { 85 var myOption = new Option(as[i], i); 86 areaEle.options.add(myOption); 87 } 88 } 89 </script> 90 </html>
效果圖
AJAX-簡單的省市縣三級聯動