数据
data.js
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>省市级联</title>
</head>
<body>
<div class="box">
<select name="" id="province"></select>
<select name="" id="city"></select>
<select name="" id="county"></select>
</div>
<script src="js/data.js"></script>
<script>
window.onload= function(){
init();
}
function init(){
//将省添加到province中
let province_list = data.province_list
let city_list = data.city_list
let county_list = data.county_list
let options = '<option value="" disabled selected>请选择</option>';
for(let key in province_list){
options += '<option value="' + key + '">' +province_list[key] + '</option>';
}
let province = document.querySelector('#province');
province.innerHTML = options;
province.onchange=function(){
//取出省前面两个数字
let pre = this.value.substr(0,2);
//根据省前两位特征将所有的市添加到市的组件
options = '<option value="" disabled selected>请选择</option>';
for (let key in city_list) {
if(key.substr(0,2) == pre){
options += '<option value="' + key + '">' +city_list[key] + '</option>';
}
}
console.log(options)
let city = document.querySelector("#city")
city.innerHTML = options;
}
city.onchange=function(){
//取出省前面4个数字
let pre = this.value.substr(0,4);
//根据省前两位特征将所有的市添加到市的组件
options = '';
for (let key in county_list) {
if(key.substr(0,4) == pre){
options += '<option value="' + key + '">' +county_list[key] + '</option>';
}
}
console.log(options)
let county = document.querySelector("#county")
county.innerHTML = options;
}
}
</script>
</body>
</html>