DIV CSS 佈局教程網

基於 DOM 實作權限穿梭框:多選與全選的搬移邏輯
編輯:關於JavaScript     

後台系統常見的「權限選擇」元件:左右兩個清單,中間四個按鈕分別做選取項搬移與全部搬移。實作關鍵在於搬移 DOM 節點的正確寫法。

搬移勾選的項目

appendChild 有個特性:被掛上去的節點若已存在於文件其他位置,會自動從原處被移走。因此搬移只需一行 appendChild,不必先 remove。這裡仍刻意用倒序迴圈,是為了避免邊刪邊改集合造成的索引錯亂。

function selMultiple(selectSrc, selectDes) {
    for (var i = selectSrc.childNodes.length - 1; i >= 0; i--) {
        var option = selectSrc.childNodes[i];
        if (option.selected == true) {
            selectSrc.removeChild(option);
            option.selected = false;
            selectDes.appendChild(option);
        }
    }
}

function selectToRight() {
    selMultiple(document.getElementById("select1"), document.getElementById("select2"));
}

function selectToLeft() {
    selMultiple(document.getElementById("select2"), document.getElementById("select1"));
}

全部搬移

這裡示範了一個常見錯誤:childNodes 除了 option 之外還會包含空白文字節點,直接用它會得到錯誤的長度。改用 getElementsByTagName("option") 才是安全的做法。另外迴圈中每次都要取「第 0 個」,因為搬走一個之後索引會往前補位。

function selAll(selectSrc, selectDes) {
    var options = selectSrc.getElementsByTagName("option");
    var optLength = options.length;   // 必須先快取長度

    for (var i = 0; i < optLength; i++) {
        selectDes.appendChild(options[0]);   // 每次都取第 0 個
    }
    selectSrc.options.length = 0;
}

function selectToRightAll() {
    selAll(document.getElementById("select1"), document.getElementById("select2"));
}

function selectToLeftAll() {
    selAll(document.getElementById("select2"), document.getElementById("select1"));
}

頁面結構

<select id="select1" multiple="multiple" style="float:left;width:100px;height:200px;">
 <option>添加</option>
 <option>刪除</option>
 <option>修改</option>
 <option>保存</option>
 <option>查詢</option>
</select>

<div style="float:left;width:50px;">
 <input type="button" style="float:left;width:100%;" value=">"  onclick="selectToRight()" />
 <input type="button" style="float:left;width:100%;" value="<"  onclick="selectToLeft()" />
 <input type="button" style="float:left;width:100%;" value=">>" onclick="selectToRightAll()" />
 <input type="button" style="float:left;width:100%;" value="<<" onclick="selectToLeftAll()" />
</div>

<select id="select2" multiple="multiple" style="float:left;width:100px;height:200px"></select>

實務上還建議補上兩點:一是搬移後把焦點移到目標清單並捲動到搬入的項目,操作起來更順;二是表單送出時,被搬走的 option 依然會隨 select 一起提交,若需要記錄「原本有哪些、現在有哪些」,記得另外用隱藏欄位保存初始狀態。

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