萬盛學電腦網

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

jQuery 實現三級聯動下拉菜單:省市區選擇器完整實戰

需求場景:地址選擇器

  • 一級:省份
  • 二級:城市(根據省份動態加載)
  • 三級:區縣(根據城市動態加載)
  • 未選擇上級時下級隱藏
  • 選擇變更時重置下級

HTML 結構

<form>
  <div class="address-selector">
    <span class="province-wrap">
      省份:
      <select class="province">
        <option value="">請選擇省份</option>
        <option value="hebei">河北</option>
        <option value="shandong">山東</option>
      </select>
    </span>
    
    <span class="city-wrap" style="display:none;">
      城市:
      <select class="city"><option value="">請選擇城市</option></select>
    </span>
    
    <span class="area-wrap" style="display:none;">
      區縣:
      <select class="area"><option value="">請選擇區縣</option></select>
    </span>
  </div>
  
  <div class="result" style="display:none; margin-top:1rem;">
    您選擇:<span class="selected-text"></span>
  </div>
</form>

數據結構設計

const addressData = {
  hebei: {
    name: '河北',
    cities: {
      shijiazhuang: { name: '石家莊', areas: ['長安區', '橋西區', '新華區', '裕華區'] },
      cangzhou:     { name: '滄州',   areas: ['新華區', '運河區', '滄縣', '青縣'] },
      langfang:     { name: '廊坊',   areas: ['安次區', '廣陽區', '固安縣', '永清縣'] }
    }
  },
  shandong: {
    name: '山東',
    cities: {
      jinan:    { name: '濟南',  areas: ['歷下區', '市中區', '槐蔭區', '天橋區'] },
      dezhou:   { name: '德州',  areas: ['德城區', '陵縣', '寧津縣', '武城縣'] },
      qingdao:  { name: '青島',  areas: ['市南區', '市北區', '李滄區', '城陽區'] }
    }
  }
};

核心邏輯實現

$(function() {
  const $province = $('.province');
  const $city = $('.city');
  const $area = $('.area');
  const $cityWrap = $('.city-wrap');
  const $areaWrap = $('.area-wrap');
  const $result = $('.result');
  const $selectedText = $('.selected-text');
  
  // 省份變化
  $province.on('change', function() {
    const provinceKey = $(this).val();
    
    // 重置並隱藏下級
    $city.val('').empty().append('');
    $area.val('').empty().append('');
    $cityWrap.hide();
    $areaWrap.hide();
    $result.hide();
    
    if (!provinceKey) return;
    
    // 填充城市
    const cities = addressData[provinceKey]?.cities || {};
    $.each(cities, (key, city) => {
      $city.append(``);
    });
    $cityWrap.show();
  });
  
  // 城市變化
  $city.on('change', function() {
    const provinceKey = $province.val();
    const cityKey = $(this).val();
    
    $area.val('').empty().append('');
    $areaWrap.hide();
    $result.hide();
    
    if (!cityKey) return;
    
    const areas = addressData[provinceKey]?.cities[cityKey]?.areas || [];
    $.each(areas, (i, area) => {
      $area.append(``);
    });
    $areaWrap.show();
  });
  
  // 區縣變化:顯示最終結果
  $area.on('change', function() {
    const provinceName = $province.find('option:selected').text();
    const cityName = $city.find('option:selected').text();
    const areaName = $(this).val();
    
    if (areaName) {
      $selectedText.text(`${provinceName} ${cityName} ${areaName}`);
      $result.show();
    } else {
      $result.hide();
    }
  });
});

進階優化:AJAX 動態加載數據

// 省份變化時異步獲取城市
$province.on('change', function() {
  const provinceId = $(this).val();
  $cityWrap.hide(); $areaWrap.hide(); $result.hide();
  $city.val('').empty().append('');
  
  if (!provinceId) return;
  
  $.getJSON('/api/areas', { parent_id: provinceId, level: 'city' })
    .done(data => {
      $city.empty().append('');
      data.forEach(city => $city.append(``));
      $cityWrap.show();
    })
    .fail(() => {
      $city.empty().append('');
    });
});

// 城市變化時異步獲取區縣(邏輯同理)
$city.on('change', function() {
  const cityId = $(this).val();
  $areaWrap.hide(); $result.hide();
  $area.val('').empty().append('');
  
  if (!cityId) return;
  
  $.getJSON('/api/areas', { parent_id: cityId, level: 'area' })
    .done(data => {
      $area.empty().append('');
      data.forEach(area => $area.append(``));
      $areaWrap.show();
    });
});

工程化增強建議

增強點方案
數據緩存首次加載後存入 sessionStorage,二次進入無需請求
搜索/過濾選項過多時接入 Select2/Chosen 增強下拉框
鍵盤導航原生 select 已支援,自定義下拉需手動實現
無障礙訪問添加 aria-label、role="combobox"、鍵盤焦點管理
表單驗證配合 HTML5 required 或 JS 驗證庫
默認值回填編輯頁面根據數據預選三級值並觸發 change 事件

現代框架對比

框架核心實現差異
Vue 3ref 綁定選中值,watch 監聽變化觸發 API 請求,v-model 雙向綁定
ReactuseState 管理三級值,useEffect 依賴上級值發起請求,受控組件模式
Alpine.jsx-data 定義狀態,@change 觸發 fetch,x-show 控制顯隱

總結

三級聯動的核心邏輯是狀態機流轉:

  1. 上級選擇 → 觸發下級數據加載
  2. 下級數據就緒 → 顯示下級選擇器
  3. 上級變更 → 重置並隱藏所有下級
  4. 末級選擇完成 → 輸出最終結果

掌握這套「觸發 → 請求 → 渲染 → 狀態同步」的閉環模式,不僅能實現地址選擇器,還能舉一反三處理「品牌→車系→車型」、「分類→子分類→品牌」等一切層級聯動場景。

copyright © 萬盛學電腦網 all rights reserved