前置知识:
<button onclick="doSelect()">操作下拉列表</button><hr>学历:<select id="degree"><option value="0">--请选择学历--</option><option value="1">专科</option><option value="2">本科</option><option value="3">硕士</option><option value="4">博士</option></select>
点击按钮:添加新的选项框Option
/*** 添加一个option*/ //方式1// var option = document.createElement('option')// option.value = 5;// option.innerText = '博士后';// degree.appendChild(option);//方式2var option = new Option('博士后',5);degree.add(option)
Json的相关知识:
JavaScript Object Notation 是一种轻量级的数据交换格式,用于表示JavaScript对象的一种方式
采用与编程语言无关的文本格式,易于阅读和编写,同时也易于解析和生成。
/*** 定义一个json对象*/var user = {"id":1001,"name":"tom","age":20,"height":175,"address":{"province":"江苏省","city":"南京市","distinct":"秦淮区"}} console.log(user.name);console.log(users);console.log(user.height)console.log(user.address.province);console.log(user.address.city);console.log(user.address.distinct);
有了以上知识,就可以实现该功能了:
首先需要引入json数据:JOSN最新省、市、县(区)数据
这是我的文件格式:
json数据:
引入json对象:
<script src="json/province.json"></script>
body:标签里面的内容:
省份:<select id="provinceId"><option value="0">--请选择省份--</option></select>城市:<select id="cityId"><option value="0">--请选择城市--</option></select>区域:<select id="areasId"><option value="0">--请选择区域--</option></select>
<script>/*** 实现二级联动的效果*/console.log(provinces);// console.log(provinces[0].title);// console.log(provinces.length);//获取省份属性var province = document.getElementById('provinceId');var city = document.getElementById('cityId');var area = document.getElementById('areasId');for (let i = 0; i < provinces.length; i++) {var option = new Option(provinces[i].title, provinces[i].code);province.add(option);}//获取城市属性//获取省份被选中的code// province// 为省份下拉列表添加事件监听器var citiesArr;province.addEventListener('change', () => {for (let i = 0; i < provinces.length; i++) {if (province.value == provinces[i].code) {var citiesArr = provinces[i].city;}}//清空上次级联列表city.length = 1;for (let j = 0; j < citiesArr.length; j++) {var option = new Option(citiesArr[j].title, citiesArr[j].code)city.add(option);}})//获取地区var areasArr;city.addEventListener('change', () => {for (let i = 0; i < provinces.length; i++) {if (province.value == provinces[i].code) {var citiesArr = provinces[i].city;// console.log(city.value);// console.log(provinces[i].city[0].area);// console.log(provinces[i].code);for (let j = 0; j < citiesArr.length; j++) {if (city.value == citiesArr[j].code) {// console.log(citiesArr[j].area);areasArr = citiesArr[j].area;console.log(areasArr);}}}}//清空上次级联列表area.length = 1;for (let i = 0; i < areasArr.length; i++) {var option = new Option(areasArr[i].title, areasArr[i].code);area.add(option);}})</script>
实现效果如下: