萬盛學電腦網

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

JS 雙向選擇框(Shuttle/雙列表框)完整實現:增刪、排序、雙擊、取值

經典 UI 模式:左側可選項、右側已選項,支援按鈕/雙擊移動、上下排序、值聚合提交。

完整 HTML + JS

<form name="myform">
<table><tr>
  <td><select multiple name="list1" size="12" ondblclick="move(list1, list2)">
    <option value="北京">北京</option> ... </select></td>
  <td align="center">
    <button type="button" onclick="move(list1, list2)">添加 >></button><br><br>
    <button type="button" onclick="move(list2, list1)"><< 刪除</button>
  </td>
  <td><select multiple name="list2" size="12" ondblclick="move(list2, list1)"></select></td>
  <td>
    <button type="button" onclick="changePos(list2, -1)">上移</button><br>
    <button type="button" onclick="changePos(list2, 1)">下移</button>
  </td>
</tr></table>
值:<input type="text" name="city" size="40">
</form>

<script>
function move(from, to){
    for(let i=0; i 0) swap(sel, i, i-1);
    if(dir === 1 && i < sel.options.length-1) swap(sel, i, i+1);
    syncValue();
}

function swap(sel, i, j){
    const optI = sel.options[i], optJ = sel.options[j];
    const t = {text:optI.text, value:optI.value};
    optI.text = optJ.text; optI.value = optJ.value;
    optJ.text = t.text; optJ.value = t.value;
    sel.selectedIndex = j;
}
</script>

關鍵技巧

  • select.add(new Option(text, value)) 追加選項(標準 DOM)。
  • select.remove(index) 刪除選項。
  • swapNode(IE 專有)或手動交換 text/value 實現排序。
  • 隱藏 input[name=city] 聚合提交值,後端按逗號分割。

現代化重構建議

使用 <select multiple> 原生體驗一般,推薦成熟組件:

  • Select2:搜索、標籤、遠程數據、無限滾動。
  • Vue/React 組件庫:Element Plus Transfer, Ant Design Transfer, React Select — 受控組件、虛擬列表、鍵盤無障礙。
  • SortableJS:拖拽排序、跨列表移動、動畫流暢。
copyright © 萬盛學電腦網 all rights reserved