代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
<select name="" id="province">
<option value="0">---请选择省份---</option>
</select>
<select name="" id="city">
<option value="0">---请选择城市---</option>
</select>
<select name="" id="district">
<option value="0">---请选择区县---</option>
</select>
<script>
// 获取所有的省份信息
$.get('./city.json', function(res) {
// 获取省份信息
res.filter(r => r.pid === 0).forEach(r => {
let option = $('<option/>')
option.val(r.id)
option.html(r.name)
$('#province').append(option)
})
})
// 省份下拉状态改变事件
$('#province').change(function() {
// 先清空城市
$('#city>option:not(:first)').remove() //选择器写法
// $('#city').children('option').not(':first').remove() //方法
// 清空区县
$('#district').children('option').not(':first').remove()
// 获取城市编号
let provinceId = $(this).val()
if (provinceId == 0) return
// 获取对应的区县信息
$.get('./city.json', function(res) {
res.filter(r => r.pid == provinceId).forEach(r => {
let option = $('<option/>')
option.val(r.id)
option.html(r.name)
$('#city').append(option)
})
})
})
// 城市下拉状态改变事件
$('#city').change(function() {
// 先清空区县
$('#district').children('option').not(':first').remove()
// 获取省份编号
let cityId = $(this).val()
if (cityId == 0) return
// 获取省份对应的城市信息
$.get('./city.json', function(res) {
res.filter(r => r.pid == cityId).forEach(r => {
let option = $('<option/>')
option.val(r.id)
option.html(r.name)
$('#district').append(option)
})
})
})
</script>
</body>
</html>
JSON文件:
[
{
"id":1,
"name":"江苏省",
"pid":0
},
{
"id":101,
"name":"南京市",
"pid":1
},
{
"id":10101,
"name":"秦淮区",
"pid":101
},
{
"id":10102,
"name":"玄武区",
"pid":101
},
{
"id":102,
"name":"苏州",
"pid":1
},
{
"id":10201,
"name":"姑苏区",
"pid":102
},
{
"id":10202,
"name":"虎丘区",
"pid":102
},
{
"id":2,
"name":"浙江省",
"pid":0
},
{
"id":201,
"name":"杭州市",
"pid":2
},
{
"id":20101,
"name":"江干区",
"pid":201
},
{
"id":20102,
"name":"滨江区",
"pid":201
},
{
"id":202,
"name":"温州市",
"pid":2
},
{
"id":20201,
"name":"鹿城区",
"pid":202
},
{
"id":20202,
"name":"龙湾区",
"pid":202
},
{
"id":3,
"name":"安徽省",
"pid":0
},
{
"id":301,
"name":"合肥市",
"pid":3
},
{
"id":30101,
"name":"蜀山区",
"pid":301
},
{
"id":30102,
"name":"庐阳区",
"pid":301
},
{
"id":302,
"name":"马鞍山市",
"pid":3
},
{
"id":30201,
"name":"花山区",
"pid":302
},
{
"id":30202,
"name":"雨山区",
"pid":302
}
]