一個簡單的三級聯動。數組
<div class="editInput"> <select id="province"><option>選擇省</option></select> <select id="city"><option>選擇市</option></select> <select id="area"><option>選擇區</option></select> </div>
同時引入了一個city.js的文件,這是省市列表。就是數組,也能夠僞裝咱們請求到的數據吧。裏面的格式是這樣的:app
兩個特別大的數組,哈哈哈spa
我就直接貼出來js文件了。3d
//select本地聯動
var pro_select = document.getElementById("province");
var city_select = document.getElementById("city"); var area_select = document.getElementById("area"); //加載省份 for(var i in province){ var opt = document.createElement("option"); opt.innerText = province[i].name; opt.setAttribute("value", province[i].id); pro_select.appendChild(opt); } //給省份添加change事件,選擇省份,獲取城市 pro_select.onchange = function(){ //獲取省份ID var proid = pro_select.value; //先清除原來的城市數據 city_select.innerHTML = "<option>選擇市</option>"; area_select.innerHTML = "<option>選擇區</option>"; //根據省份id獲取 城市列表(遍歷省份去匹配) for(var i in province){ if(province[i].id == proid){ var citys = province[i].city; //遍歷城市列表 for(var j in citys){ var opt = document.createElement("option"); opt.innerText = citys[j].name; opt.setAttribute("value", citys[j].id); city_select.appendChild(opt); } } } } //給城市添加change事件,選擇城市,獲取區縣 city_select.onchange = function(){ //獲取城市ID var cityid = city_select.value; //先清除原來的城市數據 area_select.innerHTML = "<option>選擇區</option>"; //根據城市ID獲取區縣列表 for(var i in area){ if(area[i].pid == cityid){ var opt = document.createElement("option"); opt.innerText = area[i].name; opt.setAttribute("value", area[i].id); area_select.appendChild(opt); } } }
結果:code