在页面中制作一个省、市、区3级联动的下拉菜单,根据选择的省份(至少3个)显示对应的城市(至少3个)下拉菜单,根据选择的城市显示对应的区域(所有)下拉菜单。
时间: 2023-12-14 18:39:58 浏览: 199
好的,这个可以用 HTML、CSS 和 JavaScript 来实现。首先我们需要一个包含所有省份、城市和区域的数据,可以使用 JSON 格式来表示。例如:
```json
{
"江苏省": {
"南京市": ["玄武区", "秦淮区", "建邺区", "鼓楼区"],
"苏州市": ["姑苏区", "吴中区", "相城区", "虎丘区"],
"无锡市": ["锡山区", "惠山区", "滨湖区", "梁溪区"]
},
"浙江省": {
"杭州市": ["西湖区", "拱墅区", "上城区", "下城区"],
"宁波市": ["海曙区", "江东区", "江北区", "鄞州区"],
"温州市": ["鹿城区", "龙湾区", "瓯海区", "洞头区"]
},
"广东省": {
"广州市": ["天河区", "海珠区", "荔湾区", "越秀区"],
"深圳市": ["福田区", "罗湖区", "南山区", "宝安区"],
"珠海市": ["香洲区", "金湾区", "斗门区", "横琴新区"]
}
}
```
然后我们可以先在 HTML 中创建 3 个空的下拉菜单,分别对应省、市、区:
```html
<select id="province"></select>
<select id="city"></select>
<select id="area"></select>
```
接着使用 JavaScript 动态填充省份下拉菜单:
```javascript
const data = { /* 省市区数据 */ };
const provinceSelect = document.querySelector("#province");
// 填充省份下拉菜单
for (const province in data) {
const option = document.createElement("option");
option.value = province;
option.text = province;
provinceSelect.add(option);
}
```
然后监听省份下拉菜单的 `change` 事件,在选择省份后动态填充城市下拉菜单:
```javascript
const data = { /* 省市区数据 */ };
const provinceSelect = document.querySelector("#province");
const citySelect = document.querySelector("#city");
// 填充省份下拉菜单
for (const province in data) {
const option = document.createElement("option");
option.value = province;
option.text = province;
provinceSelect.add(option);
}
// 动态填充城市下拉菜单
provinceSelect.addEventListener("change", () => {
const province = provinceSelect.value;
citySelect.innerHTML = "";
for (const city of Object.keys(data[province])) {
const option = document.createElement("option");
option.value = city;
option.text = city;
citySelect.add(option);
}
});
```
最后再监听城市下拉菜单的 `change` 事件,在选择城市后动态填充区域下拉菜单:
```javascript
const data = { /* 省市区数据 */ };
const provinceSelect = document.querySelector("#province");
const citySelect = document.querySelector("#city");
const areaSelect = document.querySelector("#area");
// 填充省份下拉菜单
for (const province in data) {
const option = document.createElement("option");
option.value = province;
option.text = province;
provinceSelect.add(option);
}
// 动态填充城市下拉菜单
provinceSelect.addEventListener("change", () => {
const province = provinceSelect.value;
citySelect.innerHTML = "";
for (const city of Object.keys(data[province])) {
const option = document.createElement("option");
option.value = city;
option.text = city;
citySelect.add(option);
}
});
// 动态填充区域下拉菜单
citySelect.addEventListener("change", () => {
const province = provinceSelect.value;
const city = citySelect.value;
areaSelect.innerHTML = "";
for (const area of data[province][city]) {
const option = document.createElement("option");
option.value = area;
option.text = area;
areaSelect.add(option);
}
});
```
这样就完成了一个简单的省市区 3 级联动的下拉菜单。
阅读全文