萬盛學電腦網

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

省市聯動下拉菜單:從 VBScript 到現代 JavaScript 實現

歷史方案回顧:VBScript (僅 IE 支持)

原文使用 <script language="vbscript"> 定義省市數據數組,onChange="vbscript:test me,ns_city" 調用 VBScript 函數填充城市下拉框。**此方案僅在 IE 中工作,現代瀏覽器完全不支持,已淘汰。**

現代標準實現(純 JS + JSON 數據)

1. 數據結構(JSON 文件或內嵌)


// city-data.js
const provinceCityData = {
    "北京市": ["東城區","西城區","朝陽區","豐台區","石景山區","海淀區","門頭溝區","房山區","通州區","順義區","昌平區","大興區","懷柔區","平谷區","密雲區","延慶區"],
    "上海市": ["黃浦區","徐匯區","長寧區","靜安區","普陀區","虹口區","楊浦區","閔行區","寶山區","嘉定區","浦東新區","金山區","松江區","青浦區","奉賢區","崇明區"],
    "廣東省": ["廣州市","深圳市","珠海市","汕頭市","佛山市","韶關市","湛江市","肇慶市","惠州市","梅州市","汕尾市","河源市","陽江市","清遠市","東莞市","中山市","潮州市","揭陽市","雲浮市"],
    // ... 其餘省份
    "台灣省": ["台北市","高雄市","台中市","台南市","新竹市","基隆市","嘉義市","桃園市","新北市","宜蘭縣","新竹縣","苗栗縣","彰化縣","南投縣","雲林縣","嘉義縣","屏東縣","台東縣","花蓮縣","澎湖縣","金門縣","連江縣"]
};

2. 核心邏輯(Vanilla JS,無依賴)


class ProvinceCitySelector {
    constructor(provinceSel, citySel, data = provinceCityData) {
        this.provinceEl = typeof provinceSel === 'string' ? document.querySelector(provinceSel) : provinceSel;
        this.cityEl = typeof citySel === 'string' ? document.querySelector(citySel) : citySel;
        this.data = data;
        this._init();
    }
    
    _init() {
        if (!this.provinceEl || !this.cityEl) return;
        
        // 填充省份
        this.provinceEl.innerHTML = '' +
            Object.keys(this.data).map(p => ``).join('');
        
        // 綁定變化事件
        this.provinceEl.addEventListener('change', () => this._updateCities());
        
        // 初始化城市框
        this._updateCities();
    }
    
    _updateCities() {
        const province = this.provinceEl.value;
        const cities = this.data[province] || [];
        
        this.cityEl.innerHTML = '' +
            cities.map(c => ``).join('');
        
        this.cityEl.disabled = !cities.length;
        
        // 觸發 change 事件供業務監聽
        this.cityEl.dispatchEvent(new Event('change', { bubbles: true }));
    }
    
    // 程式化設置值(如編輯回顯)
    setValue(province, city) {
        this.provinceEl.value = province;
        this._updateCities();
        // 異步確保 options 已渲染
        requestAnimationFrame(() => { this.cityEl.value = city || ''; });
    }
    
    // 獲取值
    getValue() {
        return { province: this.provinceEl.value, city: this.cityEl.value };
    }
}

// 使用
document.addEventListener('DOMContentLoaded', () => {
    window.pcSelector = new ProvinceCitySelector('#province', '#city');
    
    // 業務監聽
    document.getElementById('city').addEventListener('change', e => {
        console.log('選中:', window.pcSelector.getValue());
    });
});

3. HTML


<select id="province" class="form-select"></select>
<select id="city" class="form-select" disabled></select>

<style>
.form-select { padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; min-width: 150px; }
.form-select:disabled { background: #f5f5f5; color: #999; }
</style>

進階增強

功能實現要點
三級聯動(省市區)數據結構改為 {省: {市: [區]}},增加區縣 select,鏈式監聽
搜索/過濾引入 choices.js、select2 或原生 <datalist> + input
異步加載數據構造函數接受 fetch('/api/regions') Promise,await 後初始化
鍵盤導航/無障礙原生 select 已完美支持,無需額外處理
移動端優化原生 select 在 iOS/Android 會調用系統選擇器,體驗最佳
國際化數據文件按語言分離,i18n 運行時加載對應語言包

對比總結

維度VBScript 方案現代 JS 方案
瀏覽器支持僅 IE所有現代瀏覽器(含移動端)
數據維護硬編碼在腳本中獨立 JSON 文件,易維護、可異步加載
代碼結構過程式、全局污染ES6 類封裝、模塊化、可復用、可測試
擴展性極難輕鬆支持三級聯動、搜索、異步、國際化
性能阻塞解析非阻塞、可懶加載

總結

省市聯動是表單交互的基礎組件。**棄用 VBScript,拥抱標準 JS + JSON 數據**。封裝為 ProvinceCitySelector 類,暴露 setValue/getValue,配合原生 <select> 的無障礙、移動端原生選擇器優勢,即得生產級解決方案。數據源建議維護為獨立 JSON 文件或 API 接口,前端按需加載。

copyright © 萬盛學電腦網 all rights reserved