<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.select-container {
margin:20px auto;
width: 610px;
}
select {
width: 200px;
height: 25px;
line-height: 25px;
border-radius: 5px;
border: solid 1px #ccc;
}
</style>
</head>
<body>
<div class="select-container">
<select id="province"> <option value="" disabled selected>请选择省份</option></select>
<select id="city"> <option value="" disabled selected>请选择城市</option></select>
<select id="county"> <option value="" disabled selected>请选择区县</option></select>
</div>
<script>
const provTag = document.getElementById('province');
const cityTag = document.getElementById('city');
const countyTag = document.getElementById('county');
let provinces = null;
// 1.获取省份数据
async function fetchData(url) {
try {
const response = await fetch('../data/provinces.json', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
const data = await response.json();
return data;
} catch (error) {
console.log("fetct data error:",error);
}
}
// 2.初始化数据
// 2.1.省下拉列表初始化
function initProv() {
for (province of provinces) {
//创建option元素 <option value = '21000'>辽宁省</option>
let opt = new Option(province.text, province.code ,false, false);
provTag.appendChild(opt);
}
// 初始化市下拉列表
initCity(provTag.value);
}
// 2.2.市下拉列表初始化
function initCity(currentProv) {
cityTag.innerHTML = '<option value="" disabled selected>请选择城市</option>';
for (province of provinces) {
if (province.code == currentProv) {
for (city of province.cities) {
let opt = new Option(city.text, city.code,false,false);
cityTag.appendChild(opt);
}
break;
}
}
// 初始化区县下拉列表
initCounty(currentProv,cityTag.value);
}
// 2.3.区县下拉列表初始化
function initCounty(currentProv,currentCity) {
countyTag.innerHTML = '<option value="" disabled selected>请选择区县</option>';
for (province of provinces) {
if (province.code == currentProv) {
for (city of province.cities) {
if (city.code == currentCity) {
for (county of city.counties) {
let opt = new Option(county.text, county.code,false,false);
countyTag.appendChild(opt);
}
break;
}
}
}
}
}
// 3.列表联动实现
fetchData('../data/provinces.json').then(data=>{
provinces = data;
initProv(data);
})
// 4.监听省市区县下拉列表变化
provTag.onchange = ()=>{initCity(provTag.value);console.log("选定的省:"+provTag.value)};
cityTag.onchange = ()=>{initCounty(provTag.value,cityTag.value);console.log("选定的市:"+cityTag.value)};
countyTag.onchange = ()=>{console.log("选定的区县:"+countyTag.value)};
</script>
</body>
</html>
JavaScript省市区县选择三级联动实现
于 2024-06-04 15:06:11 首次发布