<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入jQuery库 --> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <title>三级联动实例</title> </head> <body> <!-- 省份下拉列表 --> <select id="province"> <option value="">请选择省份</option> </select> <!-- 城市下拉列表 --> <select id="city"> <option value="">请选择城市</option> </select> <!-- 区域下拉列表 --> <select id="area"> <option value="">请选择区域</option> </select> <!-- 提交按钮 --> <button type="button" id="submit">提交</button> <script> // 定义省市区数据 const data = { "北京市": { "市辖区": ["东城区", "西城区", "朝阳区", "丰台区", "石景山区"], "县": ["密云县", "延庆县"] }, "上海市": { "市辖区": ["黄浦区", "徐汇区", "长宁区", "静安区", "普陀区"], "县": ["崇明县"] }, "广东省": { "广州市": ["天河区", "越秀区", "海珠区", "荔湾区", "番禺区"], "深圳市": ["福田区", "罗湖区", "南山区", "宝安区", "龙岗区"], "珠海市": ["香洲区", "斗门区", "金湾区"] } // 可以根据实际情况添加更多省市区数据 }; // 渲染省份列表 function renderProvince() { let provinceSelect = document.getElementById("province"); for (let province in data) { let option = document.createElement("option"); option.value = province; option.innerHTML = province; provinceSelect.appendChild(option); } } // 渲染城市列表 function renderCity(province) { let citySelect = document.getElementById("city"); citySelect.innerHTML = "<option value=''>请选择城市</option>"; if (province) { let cities = data[province]; for (let city in cities) { let option = document.createElement("option"); option.value = city; option.innerHTML = city; citySelect.appendChild(option); } } } // 渲染区域列表 function renderArea(province, city) { let areaSelect = document.getElementById("area"); areaSelect.innerHTML = "<option value=''>请选择区域</option>"; if (province && city) { let areas = data[province][city]; for (let area of areas) { let option = document.createElement("option"); option.value = area; option.innerHTML = area; areaSelect.appendChild(option); } } } // 检查是否选择 function checkSelected() { let province = document.getElementById("province").value; let city = document.getElementById("city").value; let area = document.getElementById("area").value; if (province && city && area) { alert("您选择了:" + province + " - " + city + " - " + area); } else { alert("请选择完整的省市区!"); } } // 监听省份变化事件 document.getElementById("province").addEventListener("change", function() { let province = this.value; renderCity(province); renderArea(province, ""); }); // 监听城市变化事件 document.getElementById("city").addEventListener("change", function() { let province = document.getElementById("province").value; let city = this.value; renderArea(province, city); }); // 监听提交按钮点击事件 document.getElementById("submit").addEventListener("click", function() { checkSelected(); }); // 初始化 renderProvince(); </script> </body> </html>