jQuery实现省市区三级联动(本地json文件)
作者:互联网
1、json数据来源
2、HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<select name="" class="provinces">
</select>
<select name="" class="city">
</select>
<select name="" class="town">
</select>
</body>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="index.js" type="text/javascript" charset="utf-8"></script>
</html>
3、js代码
$(document).ready(function(){
$.getJSON('address.json',function(data){
/**
* @param {Object} id首个select框
*/
// $('.provinces')
var provinces = data.result[0]
for(let i=0;i<provinces.length;i++){
var option = document.createElement('option')
$(option).attr('id',provinces[i].id)
option.innerText = provinces[i].fullname
var text = provinces[i].fullname
$('.provinces').append(option)
}
$('.provinces').change(function(){
getCity($('.provinces option:selected').attr('id'))
//自动触发change事件
$('.city').trigger('change');
})
$('.city').change(function(){
getTown($('.city option:selected').attr('id'))
})
function getCity(id){
$('.city').empty()
var city = data.result[1]
for(let i=0;i<city.length;i++){
if(id.substring(0,2)==city[i].id.substring(0,2)){
var option = document.createElement('option')
$(option).attr('id',city[i].id)
option.innerText = city[i].fullname
var text = city[i].fullname
$('.city').append(option)
}
}
}
function getTown(id){
$('.town').empty()
var down = data.result[2]
for(let i=0;i<down.length;i++){
if(id.substring(0,4)==down[i].id.substring(0,4)){
var option = document.createElement('option')
$(option).attr('id',down[i].id)
option.innerText = down[i].fullname
var text = down[i].fullname
$('.town').append(option)
}
}
}
})
})
4、 实现效果
点击省份相应的市和县会更改
标签:jQuery,city,provinces,option,function,json,var,省市区,id 来源: https://blog.csdn.net/qq_43498002/article/details/118408468