DIV CSS 佈局教程網

JavaScript 多級聯動下拉選單:以平行陣列實作三層依賴選擇
編輯:關於JavaScript     

省一市區、類別小類、國家州城市——這類「上層選了,下層選項才跟著變」的聯動選單,幾乎每個表單系統都用得到。本文用一組平行陣列實作三層聯動,並說明這個寫法為什麼可以擴展到任意層數。

資料結構設計

關鍵是為每個選項準備兩份對應的陣列:一份存文字(arrItems),一份存它屬於哪個群組(arrItemsGrp)。群組編號對應上一層選單的 value。

<SCRIPT LANGUAGE="JavaScript">
// 第二層:文字與所屬群組
var arrItems1 = new Array();
var arrItemsGrp1 = new Array();
arrItems1[3] = "列二";   arrItemsGrp1[3] = 1;
arrItems1[4] = "列二三"; arrItemsGrp1[4] = 1;
arrItems1[5] = "列二四"; arrItemsGrp1[5] = 1;
arrItems1[6] = "列三";   arrItemsGrp1[6] = 2;
arrItems1[7] = "列三一"; arrItemsGrp1[7] = 2;
arrItems1[0] = "列四";   arrItemsGrp1[0] = 3;
arrItems1[1] = "列四一"; arrItemsGrp1[1] = 3;
arrItems1[2] = "列四二"; arrItemsGrp1[2] = 3;

// 第三層:群組編號對應的是「第二層選項的索引」
var arrItems2 = new Array();
var arrItemsGrp2 = new Array();
arrItems2[21] = "列4-0";   arrItemsGrp2[21] = 0;
arrItems2[22] = "列4-1";   arrItemsGrp2[22] = 0;
arrItems2[31] = "列41-0";  arrItemsGrp2[31] = 1;
arrItems2[34] = "列41-1";  arrItemsGrp2[34] = 1;
arrItems2[35] = "列42-0";  arrItemsGrp2[35] = 2;
arrItems2[99] = "列24-2";  arrItemsGrp2[99] = 5;
arrItems2[100] = "列24-1"; arrItemsGrp2[100] = 5;
arrItems2[57] = "列24-0";  arrItemsGrp2[57] = 5;
arrItems2[101] = "列2-0";  arrItemsGrp2[101] = 3;
arrItems2[102] = "列2-1";  arrItemsGrp2[102] = 3;
arrItems2[103] = "列23-0"; arrItemsGrp2[103] = 4;
arrItems2[104] = "列23-1"; arrItemsGrp2[104] = 4;
arrItems2[105] = "列3-0";  arrItemsGrp2[105] = 6;
arrItems2[106] = "列3-1";  arrItemsGrp2[106] = 6;
arrItems2[200] = "列31-0"; arrItemsGrp2[200] = 7;
arrItems2[201] = "列31-1"; arrItemsGrp2[201] = 7;
arrItems2[203] = "列31-2"; arrItemsGrp2[203] = 7;

// 核心:依上層選取值,重建下層選項
function selectChange(control, controlToPopulate, ItemArray, GroupArray) {
  var myEle, x;

  // 一、清空下層所有既有選項(含剛才插入的預設項)
  for (var q = controlToPopulate.options.length; q >= 0; q--) {
    controlToPopulate.options[q] = null;
  }

  // 二、若改動的是第一層,第三層也要一起清空
  if (control.name == "firstChoice") {
    for (var q = myChoices.thirdChoice.options.length; q >= 0; q--) {
      myChoices.thirdChoice.options[q] = null;
    }
  }

  // 三、先放一個預設項,避免下層空蕩蕩
  myEle = document.createElement("option");
  myEle.value = 0;
  myEle.text = "[請選擇]";
  controlToPopulate.add(myEle, null);

  // 四、逐一比對群組編號,符合的就加進去
  for (x = 0; x < ItemArray.length; x++) {
    if (GroupArray[x] == control.value) {
      myEle = document.createElement("option");
      myEle.value = x;
      myEle.text = ItemArray[x];
      controlToPopulate.add(myEle, null);
    }
  }
}
</script>

注意 add() 的第二個參數。標準簽名是 add(newOption, beforeOption),舊 IE 則是 add(newOption, index)。省略第二個參數在部分環境會拋錯,這裡明確傳 null 表示「加在最後」。

HTML 與事件串接

<form name="myChoices">
<table align="center">
<tr>
<td>
  <SELECT id="firstChoice" name="firstChoice"
    onchange="selectChange(this, myChoices.secondChoice, arrItems1, arrItemsGrp1);">
    <option value="0">列表一</option>
    <option value="1">列表二</option>
    <option value="2">列表三</option>
    <option value="3">列表四</option>
  </SELECT>
</td>
<td>
  <SELECT id="secondChoice" name="secondChoice"
    onchange="selectChange(this, myChoices.thirdChoice, arrItems2, arrItemsGrp2);">
  </SELECT>
  <SELECT id="thirdChoice" name="thirdChoice">
  </SELECT>
</td>
</tr>
</table>
</form>

整個設計的美感在於遞迴的一致性:selectChange 完全不知道自己在第幾層,它只負責「清空下一層、依群組編號填入符合的選項」。第一層的 value 對應第二層的群組,第二層的 value 又對應第三層的群組,層層相扣。因此要加到第四層、第五層,只需多準備一組陣列並多串一個 onchange。

這個寫法的問題與改良

平行陣列容易錯位

用兩個陣列靠索引對齊,只要有一筆資料打錯索引,就會產生難以察覺的錯誤。改用單一物件結構會安全得多:

var tree = {
  '1': [{ text: '列二', value: 'a' }, { text: '列二三', value: 'b' }],
  '2': [{ text: '列三', value: 'c' }],
  'a': [{ text: '列二之一', value: 'a1' }]
};

function fill(select, list) {
  select.innerHTML = '';
  (list || []).forEach(function (item) {
    var opt = document.createElement('option');
    opt.value = item.value;
    opt.textContent = item.text;
    select.appendChild(opt);
  });
}

用 appendChild 而非 add,也能一次擺脫跨瀏覽器的參數型別差異。

用 dataset 取代 name 判斷

if (control.name == "firstChoice") 這種字串比對很脆弱。改成在元素上標記 data-level="1",或直接為每個 select 傳入「它的下一層是誰」的參照,語意會清楚很多。

記得處理「已選值保留」

實務上常見需求是表單驗證失敗後回填。若上層被還原成某個值,下層必須跟著重建並選回原本的項目。上面的實作每次都清空,這部分需要額外處理。

載入效能

三層行政區資料動輒數千筆,全部塞進前端 JS 會拖慢首屏。改用 fetch 在被選擇時才向後端索取下一層,是規模化之後的必然選擇,同時要注意加上 debounce 與錯誤處理。

聯動選單的核心觀念其實只有一句:下層的選項集合,是上層當前值的函式。把這句話想清楚,實作方式就有很多種,平行陣列只是其中最直接的一種。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved