萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> javascript基於DOM實現省市級聯下拉框的方法

javascript基於DOM實現省市級聯下拉框的方法

   本文實例講述了javascript基於DOM實現省市級聯下拉框的方法。分享給大家供大家參考。具體實現方法如下:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>省市級聯下拉框</title> <script type="text/javascript"> var provs = { "江西省": ["南昌市", "景德鎮", "九江", "鷹潭", "萍鄉", "新馀", "贛州", "吉安", "宜春", "撫州", "上饒"], "福建省": ["福州", "廈門", "莆田", "三明", "泉州", "漳州", "南平", "龍巖", "寧德"], "河北省": ["石家莊", "邯鄲", "邢台", "保定", "張家口", "承德", "廊坊", "唐山", "秦皇島", "滄州", "衡水"] }; function loadProv() { //加載省份數據 var prov = document.getElementById("prov"); for (var key in provs) { var provName = key; var optProv = document.createElement("option"); optProv.value = provName; optProv.innerText = provName; prov.appendChild(optProv); } } function provChange() { var prov = document.getElementById("prov"); var city = document.getElementById("city"); var provName = prov.value; //如果沒有選擇省份,則把城市下拉框隱藏 if (provName == "none") { city.style.display = "none"; return; } else { city.style.display = ""; } var citys = provs[provName]; //city.options.length = 0; //用這種方法也可以清空原始列表 //清空城市的原始數據 for (var i = city.childNodes.length - 1; i >= 0; i--) { var child = city.childNodes[i]; city.removeChild(child); } //添加新的城市數據 for (var i = 0; i < citys.length; i++) { var optCity = document.createElement("option"); optCity.value = citys[i]; optCity.innerText = citys[i]; city.appendChild(optCity); } } </script> </head> <body onload="loadProv()"> <select id="prov" onchange="provChange()"> <option value="none">請選擇省</option> </select> <select id="city" style="display:none"></select> </body> </html>

  希望本文所述對大家的javascript程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved