js实现省市区(县)三级联动
实现效果如下:
js文件过大,一万多行就不上传了,如有需要请评论,下面是js文件data的基本数据图
实现代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实现省市区三级联动</title>
<script src="area-json.js"></script>
</head>
<body>
<select name="" id="province">
<option value="">--请选择--</option>
</select>
<select name="" id="city">
<option value="">--请选择--</option>
</select>
<select name="" id="area">
<option value="">--请选择--</option>
</select>
<script>
// 遍历省数据
var prov = document.getElementById('province');
var city = document.getElementById('city');
var area = document.getElementById('area');
data.forEach(function(item,i){
// 在prov上添加option
prov.add(new Option(item.name,i));
})
prov.onchange = function(){
// 将上一次的数据全部清空
city.innerHTML = ""
area.innerHTML = ""
// 获取当前选中元素的下标
var pindex = prov.selectedIndex - 1;
// console.log(pindex);
// 将第二级数据遍历到city的select中去
// 判断当前二级children存不存在
if(data[pindex].children){
data[pindex].children.forEach(function(item,i){
city.add(new Option(item.name,i));
})
// 只要一个默认值
if(data[pindex].children[0].children){
data[pindex].children[0].children.forEach(function(item,i){
area.add(new Option(item.name,i));
})
}
}
}
city.onchange = function(){
// 将上一次的数据全部清空
area.innerHTML = ""
// 获取当前选中元素的下标
var pindex = prov.selectedIndex-1;
var aindex = city.selectedIndex;
// 将第二级数据遍历到city的select中去
// 判断当前二级children存不存在
if(data[pindex].children[aindex].children){
data[pindex].children[aindex].children.forEach(function(item,i){
area.add(new Option(item.name,i));
})
}
}
</script>
</body>
</html>