萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現三級聯動選單:省市區數據結構與動態渲染

數據結構設計

採用三層嵌套數組,索引對應層級關係:

// 省份
var provinces = ['北京', '上海', '山東'];

// 城市:二維數組,第一維對應省份索引
var cities = [
  ['東城', '昌平', '海澱'],           // 北京
  ['浦東', '高新區'],                 // 上海
  ['濟南', '青島']                    // 山東
];

// 區縣:三維數組,[省索引][市索引] = 區數組
var areas = [
  [ // 北京
    ['東城1', '東城2', '東城3'],      // 東城
    ['昌平1', '昌平2', '昌平3'],      // 昌平
    ['海澱1', '海澱2', '海澱3']       // 海澱
  ],
  [ // 上海
    ['浦東1', '浦東2', '浦東3'],      // 浦東
    ['高新區1', '高新區2', '高新區3'] // 高新區
  ],
  [ // 山東
    ['濟南1', '濟南2'],               // 濟南
    ['青島1', '青島2']                // 青島
  ]
];

HTML 結構

<select id="province" onchange="loadCities(this)">
  <option value="-1">請選擇省份</option>
</select>

<select id="city" onchange="loadAreas(this)" disabled>
  <option value="-1">請選擇城市</option>
</select>

<select id="area" disabled>
  <option value="-1">請選擇區縣</option>
</select>

核心邏輯

var currentProvinceIndex = -1;

// 初始化省份
function initProvinces() {
  var sel = document.getElementById('province');
  provinces.forEach(function(name, idx) {
    sel.add(new Option(name, idx));
  });
}

// 省份變更 -> 載入城市
function loadCities(provinceSelect) {
  var citySel = document.getElementById('city');
  var areaSel = document.getElementById('area');
  
  // 重置下級
  citySel.length = 1; // 保留「請選擇」
  areaSel.length = 1;
  citySel.disabled = true;
  areaSel.disabled = true;
  
  var pIdx = parseInt(provinceSelect.value, 10);
  if (pIdx === -1) return;
  
  currentProvinceIndex = pIdx;
  var cityList = cities[pIdx];
  
  cityList.forEach(function(name, idx) {
    citySel.add(new Option(name, idx));
  });
  citySel.disabled = false;
}

// 城市變更 -> 載入區縣
function loadAreas(citySelect) {
  var areaSel = document.getElementById('area');
  areaSel.length = 1;
  areaSel.disabled = true;
  
  var cIdx = parseInt(citySelect.value, 10);
  if (cIdx === -1) return;
  
  var areaList = areas[currentProvinceIndex][cIdx];
  areaList.forEach(function(name, idx) {
    areaSel.add(new Option(name, idx));
  });
  areaSel.disabled = false;
}

// 頁面加載初始化
document.addEventListener('DOMContentLoaded', initProvinces);

進階增強

1. 數據外部化(JSON 文件/接口)

// 實際項目中從後端獲取
fetch('/api/regions')
  .then(r => r.json())
  .then(data => {
    provinces = data.provinces;
    cities = data.cities;
    areas = data.areas;
    initProvinces();
  });

2. 封裝為可複用類

class Cascader {
  constructor(container, data, options = {}) {
    this.container = container;
    this.data = data; // {provinces, cities, areas}
    this.levels = options.levels || 3;
    this.selects = [];
    this.render();
  }
  
  render() {
    // 動態創建 select 元素,綁定事件
  }
  
  // ... 核心邏輯同前
}

3. 支援搜索/模糊匹配

選項過多時,將 select 替換為 input + datalist 或下拉搜索組件(如 Select2、Choices.js)。

4. 表單驗證集成

// 提交前檢查
form.addEventListener('submit', function(e) {
  if (provinceSelect.value === '-1') {
    alert('請選擇省份');
    e.preventDefault();
  }
});

完整可運行單文件版

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>三級聯動演示</title>
<style>
select { width:150px; padding:5px; margin-right:10px; }
</style></head><body>
<div>省:<select id="province"><option value="-1">請選擇</option></select></div>
<div>市:<select id="city" disabled><option value="-1">請選擇</option></select></div>
<div>區:<select id="area" disabled><option value="-1">請選擇</option></select></div>
<script>
// 上方數據結構 + 邏輯代碼
</script>
</body></html>

總結

三級聯動本質是 層級數據的索引映射 + DOM 動態更新。關鍵點:

  1. 數據結構設計清晰(陣列索引對應層級)
  2. 級聯重置:上級變更時,清空並禁用所有下級
  3. 使用 Option 構造函數創建選項,比拼接 HTML 字符串更安全、標準
  4. 實際項目中數據應從後端 API 獲取,前端僅負責渲染與交互
copyright © 萬盛學電腦網 all rights reserved