前端常見程式設計題(四):三級聯動
阿新 • • 發佈:2021-06-26
不多bb,上硬貨
html程式碼
js程式碼:
var province = document.querySelector('#province'); //省
var cityNode = document.querySelector('#city'); //市
var areaNode = document.querySelector('#area'); //區
// bind 繫結 Province 省份 function bindProvince() { // option 選項 定義下拉(select)列表中的一個選項(一個條目) var options = '<option value="-1">請選擇...</option>'; // forEach() 遍歷 city_code.forEach(function(c) { options += `<option value="${c.code}">${c.name}</option>`; }) province.innerHTML = options } bindProvince(); // bind 繫結 City 市 // code 編碼 function bindCity(provinceCode) { var qq = function(v) { return v.code === provinceCode; } // filter() 過濾 var provinceArr = city_code.filter(qq); var city = []; if (provinceArr.length > 0) { var province = provinceArr[0] city = province.city; } var options = '<option value="-1">請選擇...</option>'; var ww = function(c) { options += `<option value="${c.code}">${c.name}</option>`; } city.forEach(ww); cityNode.innerHTML = options; } bindCity("-1"); //繫結 區 function bindArea(provinceCode, cityCode) { var provinceArr = city_code.filter(function(v) { return v.code === provinceCode; }); var area = []; if (provinceArr.length > 0) { var province = provinceArr[0] var cityArr = province.city; var oneCityArr = cityArr.filter(function(c) { return c.code === cityCode; }); if (oneCityArr.length > 0) { var city = oneCityArr[0]; area = city.area; } } var options = '<option value="-1">請選擇...</option>'; area.forEach(function(c) { options += `<option value="${c.code}">${c.name}</option>`; }) areaNode.innerHTML = options; } bindArea("-1", "-1") province.addEventListener('change', function(e) { bindCity(e.target.value); bindArea(e.target.value, "-1") }) cityNode.addEventListener('change', function(e) { var provinceCode = province.value; var cityCode = e.target.value; bindArea(provinceCode, cityCode) })
因為這裡需要城市資料,所以我把資料傳到碼雲上了,有需要的小夥伴可以自己去看
連結:https://gitee.com/s272/blog-garden.git