js+ajax 实现三级下拉菜单
时间: 2023-09-03 09:16:33 浏览: 100
下面是一个简单的三级下拉菜单的实现示例:
HTML代码:
```
<select id="province">
<option value="">请选择省份</option>
<option value="1">北京</option>
<option value="2">上海</option>
<option value="3">广东</option>
</select>
<select id="city">
<option value="">请选择城市</option>
</select>
<select id="area">
<option value="">请选择区县</option>
</select>
```
JavaScript代码:
```
// 省份数据
var provinceData = [{
id: 1,
name: "北京",
cityData: [{
id: 101,
name: "北京市",
areaData: [{
id: 10101,
name: "东城区"
}, {
id: 10102,
name: "西城区"
}, {
id: 10103,
name: "朝阳区"
}]
}]
}, {
id: 2,
name: "上海",
cityData: [{
id: 201,
name: "上海市",
areaData: [{
id: 20101,
name: "黄浦区"
}, {
id: 20102,
name: "徐汇区"
}, {
id: 20103,
name: "长宁区"
}]
}]
}, {
id: 3,
name: "广东",
cityData: [{
id: 301,
name: "广州市",
areaData: [{
id: 30101,
name: "天河区"
}, {
id: 30102,
name: "白云区"
}, {
id: 30103,
name: "海珠区"
}]
}, {
id: 302,
name: "深圳市",
areaData: [{
id: 30201,
name: "福田区"
}, {
id: 30202,
name: "罗湖区"
}, {
id: 30203,
name: "南山区"
}]
}]
}];
// 绑定省份下拉框的change事件
document.getElementById("province").addEventListener("change", function() {
var provinceId = this.value;
var citySelect = document.getElementById("city");
var areaSelect = document.getElementById("area");
// 清空城市和区县下拉框
citySelect.innerHTML = '<option value="">请选择城市</option>';
areaSelect.innerHTML = '<option value="">请选择区县</option>';
// 根据选择的省份动态加载城市下拉框
if (provinceId) {
for (var i = 0; i < provinceData.length; i++) {
if (provinceData[i].id == provinceId) {
for (var j = 0; j < provinceData[i].cityData.length; j++) {
var cityOption = document.createElement("option");
cityOption.value = provinceData[i].cityData[j].id;
cityOption.innerHTML = provinceData[i].cityData[j].name;
citySelect.appendChild(cityOption);
}
break;
}
}
}
});
// 绑定城市下拉框的change事件
document.getElementById("city").addEventListener("change", function() {
var cityId = this.value;
var areaSelect = document.getElementById("area");
// 清空区县下拉框
areaSelect.innerHTML = '<option value="">请选择区县</option>';
// 根据选择的城市动态加载区县下拉框
if (cityId) {
for (var i = 0; i < provinceData.length; i++) {
for (var j = 0; j < provinceData[i].cityData.length; j++) {
if (provinceData[i].cityData[j].id == cityId) {
for (var k = 0; k < provinceData[i].cityData[j].areaData.length; k++) {
var areaOption = document.createElement("option");
areaOption.value = provinceData[i].cityData[j].areaData[k].id;
areaOption.innerHTML = provinceData[i].cityData[j].areaData[k].name;
areaSelect.appendChild(areaOption);
}
break;
}
}
}
}
});
```
说明:
1. 首先定义一个省份数据的数组,包含省份、城市和区县数据。
2. 在HTML中定义三个下拉框,分别为省份、城市和区县。省份下拉框默认加载所有省份数据,城市和区县下拉框默认为空。
3. 绑定省份下拉框的change事件,根据选择的省份动态加载城市下拉框,清空区县下拉框。
4. 绑定城市下拉框的change事件,根据选择的城市动态加载区县下拉框。
阅读全文