- 数据定义:用一个对象
data
存储省和市的信息。 - 省份选择:通过遍历
data
对象,将省份添加到第一个<select>
元素中。 - 城市更新:当选择省份时,调用
updateCities
函数,更新城市下拉列表。清空之前的城市选项,然后根据选中的省份更新城市列表。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>省市级联选择</title>
</head>
<body>
<select id="province" onchange="updateCities()">
<option value="">请选择省</option>
</select>
<select id="city">
<option value="">请选择市</option>
</select>
<script>
const data = {
'省1': ['市1-1', '市1-2', '市1-3'],
'省2': ['市2-1', '市2-2'],
'省3': ['市3-1', '市3-2', '市3-3', '市3-4']
};
const provinceSelect = document.getElementById('province');
const citySelect = document.getElementById('city');
// Populate provinces
for (const province in data) {
const option = document.createElement('option');
option.value = province;
option.textContent = province;
provinceSelect.appendChild(option);
}
function updateCities() {
const selectedProvince = provinceSelect.value;
citySelect.innerHTML = '<option value="">请选择市</option>'; // Clear previous cities
if (selectedProvince) {
const cities = data[selectedProvince];
for (const city of cities) {
const option = document.createElement('option');
option.value = city;
option.textContent = city;
citySelect.appendChild(option);
}
}
}
</script>
</body>
</html>
标签:province,city,级联,const,option,js,document,data,select
From: https://blog.csdn.net/qq_61236034/article/details/141953816