DIV CSS 佈局教程網

讓列表框的選項上下移動:排序功能的實作
編輯:關於JavaScript     

有些介面需要使用者自行調整項目順序(例如自訂排序、優先度安排)。做法是交換相鄰兩項的 value 與 text,並把選取位置移到新的一格。

function listboxMove(listID, direction) {
  var listbox = document.getElementById(listID);
  var selIndex = listbox.selectedIndex;

  if (-1 == selIndex) {
    alert("請先選擇要移動的項目。");
    return;
  }

  var increment = (direction == 'up') ? -1 : 1;

  // 已達邊界則不動
  if ((selIndex + increment) < 0 ||
      (selIndex + increment) > (listbox.options.length - 1)) {
    return;
  }

  var selValue = listbox.options[selIndex].value;
  var selText  = listbox.options[selIndex].text;

  listbox.options[selIndex].value = listbox.options[selIndex + increment].value;
  listbox.options[selIndex].text  = listbox.options[selIndex + increment].text;

  listbox.options[selIndex + increment].value = selValue;
  listbox.options[selIndex + increment].text  = selText;

  listbox.selectedIndex = selIndex + increment;
}

可直接操作的示範

<select id="lsbox" name="lsbox" size="10" multiple>
  <option value="1">India</option>
  <option value="2">United States</option>
  <option value="3">China</option>
  <option value="4">Italy</option>
  <option value="5">Germany</option>
  <option value="6">Canada</option>
  <option value="7">France</option>
  <option value="8">United Kingdom</option>
</select>
<br>
<button onclick="listboxMove('lsbox', 'up');">上移</button>
<button onclick="listboxMove('lsbox', 'down');">下移</button>

兩個細節與一個更好的寫法

第一,邊界判斷是必需的。第一項再往上、最後一項再往下都會超出範圍,若不攔住會得到 undefined 並把內容清空。

第二,這裡交換的是「值與文字」,元素本身的位置並未變動。若 option 上還掛了其他屬性(例如 data-id、disabled),這個寫法不會一併搬過去,容易出錯。

更穩健的作法是不搬屬性,而是搬整個節點:

function listboxMoveNode(listID, direction) {
  var listbox = document.getElementById(listID);
  var i = listbox.selectedIndex;
  if (i < 0) { return; }

  var j = i + (direction === 'up' ? -1 : 1);
  if (j < 0 || j >= listbox.options.length) { return; }

  var opt = listbox.options[i];
  listbox.remove(i);            // 先移除
  listbox.add(opt, j);          // 再插到目標位置
  listbox.selectedIndex = j;
}

這樣做保留了 option 上的所有屬性與事件綁定。要注意 select.add() 的第二個參數在部分舊版 IE 需要傳 null 而非索引,若必須支援舊環境可包在 try-catch 裡降級處理。

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