有些介面需要使用者自行調整項目順序(例如自訂排序、優先度安排)。做法是交換相鄰兩項的 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 裡降級處理。