效果如下:

代碼如下:
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>省市區(qū)三級(jí)聯(lián)動(dòng)</title></head><body> <form> <select id="province"> <option>請(qǐng)選擇省份</option> </select> <select id="city"> <option>請(qǐng)選擇城市</option> </select> <select id="district"> <option>請(qǐng)選擇區(qū)域</option> </select>  </form> <script src="json.js"></script> <script type="text/javascript"> var proData = [], cityData = [], distData = []; var proSelect = document.getElementById("province"), citySelect = document.getElementById("city"), districtSelect = document.getElementById("district"); var curPro = "", curCity = ""; // 封裝更新選擇列表函數(shù) function fillselect(select,list){ for (var i = select.length-1; i > 0 ; i--){ select.remove(i); } list.forEach(function(data){ var option = new Option(data.name, data.sheng); option.dataset.di = data.di; select.add(option); }) } // 將數(shù)據(jù)按省、市、地區(qū)分別存儲(chǔ) dataJson.forEach(function(data){ if (data.level === 1){ proData.push(data); } if (data.level === 2){ cityData.push(data); } if (data.level === 3){ distData.push(data); } }) fillselect(proSelect,proData); // 監(jiān)聽一級(jí)省份選擇列表change事件,更新二級(jí)城市列表 proSelect.addEventListener("change",function(event){ var val = event.target.value; var list = []; cityData.forEach(function(d){ if (d.sheng === val) { list.push(d); } }) fillselect(citySelect,list); }) // 監(jiān)聽二級(jí)城市選擇列表change事件,更新三級(jí)區(qū)域列表 citySelect.addEventListener("change",function(event){ var val = event.target.value; var curIndex = event.target.selectedIndex; curCity = event.target[curIndex].dataset.di; console.log(event.target,curCity); var list = []; distData.forEach(function(d){ if (d.di === curCity && d.sheng === val) { list.push(d); } }) fillselect(districtSelect,list); }) </script></body></html>以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持武林網(wǎng)!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注