这是我找的三级联动示例,忘兄弟们看完关注下
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>三级联动示例</title> <style> body { font-family: Arial, sans-serif; background-color: #f9f9f9; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } .container { background-color: #fff; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); padding: 20px; max-width: 400px; width: 100%; } select { width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; } </style> </head> <body> <div class="container"> <select id="level1"></select> <select id="level2"></select> <select id="level3"></select> </div> <script> // 模拟数据 const data = { "中国": { "河南": ["郑州", "洛阳", "开封"], "河北": ["石家庄", "唐山", "邯郸"] }, "美国": { "加利福尼亚": ["洛杉矶", "旧金山", "圣地亚哥"], "德克萨斯": ["休斯顿", "达拉斯", "奥斯汀"] } }; function populateSelect(select, options) { select.innerHTML = ''; options.forEach(option => { const opt = document.createElement('option'); opt.value = option; opt.textContent = option; select.appendChild(opt); }); } document.addEventListener('DOMContentLoaded', function() { const level1 = document.getElementById('level1'); const level2 = document.getElementById('level2'); const level3 = document.getElementById('level3'); // 初始化第一级 populateSelect(level1, Object.keys(data)); // 监听第一级变化 level1.addEventListener('change', function() { const selectedCountry = level1.value; const provinces = Object.keys(data[selectedCountry]); populateSelect(level2, provinces); // 初始化第二级 level2.dispatchEvent(new Event('change')); }); // 监听第二级变化 level2.addEventListener('change', function() { const selectedCountry = level1.value; const selectedProvince = level2.value; const cities = data[selectedCountry][selectedProvince]; populateSelect(level3, cities); }); // 初始化第一级 level1.dispatchEvent(new Event('change')); }); </script> </body> </html>