<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
</style>
<body>
<select name="" id="province">
</select>
<select name="" id="city">
<option value="">请选择</option>
</select>
<select name="" id="town">
<option value="">请选择</option>
</select>
</body>
<script src="./jquery.min.js"></script>
<script>
$.ajax({
url: ‘./city.json‘,
success: res => {
var str = ‘<option value="">请选择</option>‘;
res = formatData(res.list);
res.forEach(({city_id,name}) => {
str += `<option value="${city_id}" class=‘active‘>${name}</option>`;
})
$(‘#province‘).append(str);
$(‘#province‘).change(function(){
$(‘#city‘).empty();
$(‘#city‘).append(‘<option value="">请选择</option>‘);
$(‘#town‘).empty();
$(‘#town‘).append(‘<option value="">请选择</option>‘);
if(!$(‘#province‘).val()){
return;
}
var city_id = $(this).val();
selectCity(res,city_id);
})
}
})
function selectCity(res,city_id){
var cityList = res.filter(item=>{
if(item.city_id == city_id){
return item;
}
})[0].list;
var str = ‘<option value="">请选择</option>‘;
cityList.forEach(({city_id,name})=>{
str += `<option value="${city_id}">${name}</option>`;
})
$(‘#city‘).empty();
$(‘#city‘).append(str);
$(‘#city‘).change(function(){
var city_id = $(this).val();
selectX(cityList,city_id);
})
}
function selectX(cityList,city_id){
var xListn = cityList.filter(item=>{
if(item.city_id == city_id){
return item;
}
})[0].list;
console.log(xListn);
var str = ‘<option value="">请选择</option>‘;
xListn.forEach(({city_id,name})=>{
str += `<option value="${city_id}">${name}</option>`;
})
$(‘#town‘).empty();
$(‘#town‘).append(str);
}
function formatData(res) {
var a = [];
for (var i = 0; i < 4; i++) {
a.push(res.shift());
}
var b = [];
var arr = res.filter(item => {
if (item.name == ‘香港‘ || item.name == ‘澳门‘) {
b.push(item);
} else {
return item;
}
})
arr.unshift({
name: ‘直辖市‘,
city_id: ‘CH99‘,
list: a
}, {
name: ‘特别行政区‘,
city_id: ‘CH98‘,
list: b
});
return arr;
}
</script>
</html>