純JS省市區聯動
阿新 • • 發佈:2018-11-10
不需要訪問後臺伺服器端,不使用Ajax,無重新整理,純JS實現的省市區三級聯動。
當省市區資料變動是隻需調正js即可。
使用方法:
<!DOCTYPE HTML> <html> <head> <title>純JS省市區聯動</title> <script type="text/javascript" src="jsAddress.js"></script> </head> <body> <div> 省:<select id="cmbProvince"></select> 市:<select id="cmbCity"></select> 區:<select id="cmbArea"></select> <br /><br /> 省:<select id="Select1"></select> 市:<select id="Select2"></select> 區:<select id="Select3"></select> <script type="text/javascript"> addressInit("cmbProvince", "cmbCity", "cmbArea", "陝西", "寶雞市", "金臺區"); addressInit("Select1", "Select2", "Select3"); </script> </div> </body> </html> 核心程式碼如下: var addressInit = function(_cmbProvince, _cmbCity, _cmbArea, defaultProvince, defaultCity, defaultArea) { var cmbProvince = document.getElementById(_cmbProvince); var cmbCity = document.getElementById(_cmbCity); var cmbArea = document.getElementById(_cmbArea); function cmbSelect(cmb, str) { for(var i=0; i<cmb.options.length; i++) { if(cmb.options[i].value == str) { cmb.selectedIndex = i; return; } } } function cmbAddOption(cmb, str, obj) { var option = document.createElement("OPTION"); cmb.options.add(option); option.innerHTML = str; option.value = str; option.obj = obj; } function changeCity() { cmbArea.options.length = 0; if(cmbCity.selectedIndex == -1)return; var item = cmbCity.options[cmbCity.selectedIndex].obj; for(var i=0; i<item.areaList.length; i++) { cmbAddOption(cmbArea, item.areaList[i], null); } cmbSelect(cmbArea, defaultArea); } function changeProvince() { cmbCity.options.length = 0; cmbCity.onchange = null; if(cmbProvince.selectedIndex == -1)return; var item = cmbProvince.options[cmbProvince.selectedIndex].obj; for(var i=0; i<item.cityList.length; i++) { cmbAddOption(cmbCity, item.cityList[i].name, item.cityList[i]); } cmbSelect(cmbCity, defaultCity); changeCity(); cmbCity.onchange = changeCity; } for(var i=0; i<provinceList.length; i++) { cmbAddOption(cmbProvince, provinceList[i].name, provinceList[i]); } cmbSelect(cmbProvince, defaultProvince); changeProvince(); cmbProvince.onchange = changeProvince; } var provinceList = [ {name:"北京", cityList:[ {name:"市轄區", areaList:["東城區","西城區","崇文區","宣武區","朝陽區","豐臺區","石景山區","海淀區","門頭溝區","房山區","通州區","順義區","昌平區","大興區","懷柔區","平谷區"]}, {name:"縣", areaList:["密雲縣","延慶縣"]} ]}, {name:"上海", cityList:[ {name:"市轄區", areaList:["黃浦區","盧灣區","徐彙區","長寧區","靜安區","普陀區","閘北區","虹口區","楊浦區","閔行區","寶山區","金山區","松江區","青浦區","南匯區","奉賢區"]}, {name:"縣", areaList:["崇明縣"]} ]} ];
例項下載:https://download.csdn.net/download/qq_27016363/10725632