基础概念: JS 城市联动菜单是一种常见的网页交互功能,通过 JavaScript 实现不同层级城市之间的联动选择。
优势:
类型:
应用场景:
可能出现的问题及原因:
解决方法:
示例代码(简单的两级联动):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>城市联动</title>
</head>
<body>
<select id="province">
<option value="">请选择省份</option>
</select>
<select id="city">
<option value="">请选择城市</option>
</select>
<script>
const provinceData = {
"广东省": ["广州市", "深圳市"],
"湖南省": ["长沙市", "株洲市"]
};
const provinceSelect = document.getElementById('province');
const citySelect = document.getElementById('city');
// 初始化省份选项
for (let province in provinceData) {
let option = document.createElement('option');
option.value = province;
option.textContent = province;
provinceSelect.appendChild(option);
}
// 省份选择变化时更新城市选项
provinceSelect.addEventListener('change', function () {
let selectedProvince = this.value;
citySelect.innerHTML = '<option value="">请选择城市</option>';
if (selectedProvince) {
let cities = provinceData[selectedProvince];
cities.forEach(city => {
let option = document.createElement('option');
option.value = city;
option.textContent = city;
citySelect.appendChild(option);
});
}
});
</script>
</body>
</html>
在上述示例中,当省份选择变化时,会相应地更新城市的选项。
领取专属 10元无门槛券
手把手带您无忧上云