html select下拉框 多级联动
时间: 2023-07-19 12:07:02 浏览: 145
javascript实现二级联动下拉框
多级联动的下拉框可以通过JavaScript实现。以下是一个简单的例子:
HTML代码:
```html
<select id="province" onchange="updateCity()">
<option value="">请选择省份</option>
<option value="江苏">江苏</option>
<option value="浙江">浙江</option>
</select>
<select id="city" onchange="updateDistrict()">
<option value="">请选择城市</option>
</select>
<select id="district">
<option value="">请选择区县</option>
</select>
```
JavaScript代码:
```javascript
var cityData = {
"江苏": ["南京", "苏州", "无锡"],
"浙江": ["杭州", "宁波", "温州"]
};
var districtData = {
"南京": ["玄武区", "鼓楼区", "建邺区"],
"苏州": ["姑苏区", "虎丘区", "吴中区"],
"无锡": ["锡山区", "惠山区", "滨湖区"],
"杭州": ["西湖区", "上城区", "下城区"],
"宁波": ["海曙区", "江东区", "江北区"],
"温州": ["鹿城区", "龙湾区", "瓯海区"]
};
function updateCity() {
var province = document.getElementById("province").value;
var citySelect = document.getElementById("city");
var districtSelect = document.getElementById("district");
citySelect.innerHTML = "<option value=''>请选择城市</option>";
districtSelect.innerHTML = "<option value=''>请选择区县</option>";
if (province != "") {
var cities = cityData[province];
for (var i = 0; i < cities.length; i++) {
var option = document.createElement("option");
option.value = cities[i];
option.innerHTML = cities[i];
citySelect.appendChild(option);
}
}
}
function updateDistrict() {
var province = document.getElementById("province").value;
var city = document.getElementById("city").value;
var districtSelect = document.getElementById("district");
districtSelect.innerHTML = "<option value=''>请选择区县</option>";
if (province != "" && city != "") {
var districts = districtData[city];
for (var i = 0; i < districts.length; i++) {
var option = document.createElement("option");
option.value = districts[i];
option.innerHTML = districts[i];
districtSelect.appendChild(option);
}
}
}
```
在这个例子中,我们定义了两个对象:cityData和districtData,分别保存了城市和区县的数据。当省份下拉框的值发生变化时,我们会根据选中的省份动态生成城市下拉框的选项。同样地,当城市下拉框的值发生变化时,我们会根据选中的城市动态生成区县下拉框的选项。
你可以根据自己的需求修改cityData和districtData对象,来实现更复杂的多级联动下拉框效果。
阅读全文