原生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>
<style>
select {
width: 200px;
margin-right: 10px;
}
</style>
</head>
<body>
<form action="">
<select name="province" id="s1">
<option value="">请选择省</option> </select
>省
<select name="city" id="s2" disabled="true">
<option value="">请选择市</option> </select
>市
<select name="county" id="s3" disabled="true">
<option value="">请选择区县</option> </select
>县
</form>
<script src="./address.js"></script>
</body>
</html>
JS部分
const forms = document.forms[0];
for (let i = 0; i < data.length; i++) {
let opt = document.createElement("option");
opt.innerHTML = data[i].value;
forms.province.appendChild(opt);
}
//省份发生改变时候触发的方法
forms.province.onchange = function () {
//根据下标判断当前是否选择了省份
if (forms.province.selectedIndex !== 0) {
forms.city.innerHTML="<option>请选择市</option>"
forms.county.innerHTML="<option>请选择区县</option>"
forms.city.disabled = false;
let currentCity = [];
for (let i = 0; i < data.length; i++) {
if (data[i].value === forms.province.value) {
currentCity = data[i].children;
}
}
for(let i=0; i<currentCity.length; i++){
let opt =document.createElement("option")
opt.innerHTML=currentCity[i].value
forms.city.appendChild(opt)
}
} else {
forms.city.disabled=true
forms.county.disabled=true
forms.city.innerHTML="<option>请选择市</option>"
forms.county.innerHTML="<option>请选择区县</option>"
}
};
forms.city.onchange=function(){
if (forms.city.selectedIndex!=0) {
forms.county.innerHTML="<option>请选择区县</option>"
forms.county.disabled=false
let currentCity=[]
let currentCounty=[]
for (let i = 0; i < data.length; i++) {
for(let j=0; j<data[i].children.length; j++){
if (data[i].children[j].value== forms.city.value) {
currentCounty=data[i].children[j].children
}
}
}
for(let i=0; i<currentCounty.length; i++){
let opt=document.createElement("option")
opt.innerHTML=currentCounty[i].value
forms.county.appendChild(opt)
}
}else{
forms.county.disabled=true
forms.county.innerHTML="<option>请选择区县</option>"
}
}
国家的省市县JS文件大家可以在https://github.com/466879168/examples/blob/master/%E4%B8%89%E7%BA%A7%E8%81%94%E5%8A%A8/address.js里面查看下载