省市下拉列表联动,HTML
时间: 2023-11-30 15:31:43 浏览: 222
可以使用原生的 HTML、JavaScript 实现省市下拉列表的联动。具体步骤如下:
1. 在 HTML 中添加两个 select 元素,分别用于显示省份和城市列表,例如:
```html
<label for="province">省份:</label>
<select id="province"></select>
<label for="city">城市:</label>
<select id="city"></select>
```
2. 定义一个包含省份和城市信息的 JavaScript 对象,例如:
```javascript
const cityData = {
"北京市": ["东城区", "西城区", "朝阳区", "海淀区", "丰台区", "石景山区", "通州区", "昌平区", "大兴区", "房山区", "门头沟区", "顺义区", "平谷区", "怀柔区", "密云区", "延庆区"],
"上海市": ["黄浦区", "卢湾区", "徐汇区", "长宁区", "静安区", "普陀区", "闸北区", "虹口区", "杨浦区", "宝山区", "闵行区", "嘉定区", "松江区", "金山区", "青浦区", "奉贤区", "崇明区"],
// 其他省市的城市信息
// ...
};
```
3. 在 JavaScript 中添加事件监听器,监听省份 select 元素的 change 事件,当省份发生变化时,动态生成对应的城市列表,例如:
```javascript
const provinceSelect = document.getElementById("province");
const citySelect = document.getElementById("city");
provinceSelect.addEventListener("change", function() {
const province = provinceSelect.value; // 获取选中的省份
const cities = cityData[province]; // 获取该省份对应的城市列表
// 清空城市列表
citySelect.innerHTML = "";
// 动态生成城市选项
for (let i = 0; i < cities.length; i++) {
const option = document.createElement("option");
option.text = cities[i];
citySelect.add(option);
}
});
```
完整的 HTML 和 JavaScript 代码如下:
```html
<label for="province">省份:</label>
<select id="province">
<option value="北京市">北京市</option>
<option value="上海市">上海市</option>
<!-- 其他省份的选项 -->
</select>
<label for="city">城市:</label>
<select id="city"></select>
<script>
const cityData = {
"北京市": ["东城区", "西城区", "朝阳区", "海淀区", "丰台区", "石景山区", "通州区", "昌平区", "大兴区", "房山区", "门头沟区", "顺义区", "平谷区", "怀柔区", "密云区", "延庆区"],
"上海市": ["黄浦区", "卢湾区", "徐汇区", "长宁区", "静安区", "普陀区", "闸北区", "虹口区", "杨浦区", "宝山区", "闵行区", "嘉定区", "松江区", "金山区", "青浦区", "奉贤区", "崇明区"],
// 其他省市的城市信息
// ...
};
const provinceSelect = document.getElementById("province");
const citySelect = document.getElementById("city");
provinceSelect.addEventListener("change", function() {
const province = provinceSelect.value; // 获取选中的省份
const cities = cityData[province]; // 获取该省份对应的城市列表
// 清空城市列表
citySelect.innerHTML = "";
// 动态生成城市选项
for (let i = 0; i < cities.length; i++) {
const option = document.createElement("option");
option.text = cities[i];
citySelect.add(option);
}
});
</script>
```
阅读全文