JS簡單實現二級聯動菜單


 1 <form method="post" action="">
 2         省/市:<select id="province" onchange="alter(this.selectedIndex)"></select>
 3         市/區:<select id="city"></select>
 4     </form>
 5     <script type="text/javascript">
 6         //定義省/直轄市數組
 7         var arr_province = ["請選擇省/直轄市","北京市","上海市","廣東省"];
 8         //定義市/區二維數組
 9         var arr_city = [
10                         ["請選擇市/區"],
11                         ["東城區","西城區","朝陽區","宣武區","昌平區","大興區","豐台區","海淀區"],
12                         ['寶山區','長寧區','豐賢區', '虹口區','黃浦區','青浦區','南匯區','徐匯區','盧灣區'],
13                         ['廣州市','惠州市','汕頭市','珠海市','佛山市','中山市','東莞市']
14                     ];
15         //獲取對象
16         var province = document.getElementById('province');
17         var city = document.getElementById('city');
18         //初始化菜單
19         onload = function () {
20             //指定省option標記的個數
21             province.length = arr_province.length;
22             //數組數據寫入<option>標記中
23             for(var i = 0; i < arr_province.length; i++){
24                 province.options[i].text = province.options[i].value = arr_province[i];
25             }
26             //設置省列表默認選項
27             var index = 0;
28             province.index = index;
29             //指定城市option標記的個數
30             city.length = arr_city[index].length;
31             //數組數據寫入option標記
32             for (var j = 0; j < arr_city[index].length; j++) {
33                 city.options[j].text = city.options[j].value = arr_city[index][j];
34             }
35         }
36         function alter(index) {
37             //修改省列表的選擇項
38             province.index = index;
39             //指定城市option標記的個數
40             city.length = arr_city[index].length;
41             //數組中的數據寫入option標記
42             for (var j = 0; j < arr_city[index].length; j++) {
43                 city.options[j].text = city.options[j].value = arr_city[index][j];
44             }
45         }
46     </script>

  運行:
  
  

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM