後台設定權限時常見這種介面:左邊是可用項目,右邊是已授予項目,中間四個箭頭按鈕負責搬移。核心操作其實只有一個——把選中的 option 從一個 select 搬到另一個 select。
<script type="text/javascript">
// 搬移「被選中」的項目
function selMultiple(selectSrc, selectDes) {
// 倒序遍歷,因為搬移會改變 childNodes 的長度
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"));
}
// 搬移「全部」項目
function selAll(selectSrc, selectDes) {
// 注意:這裡不能直接用 selectSrc.childNodes.length 當迴圈上界。
// childNodes 除了 option 還包含空白文字節點,
// 實際節點數會比 option 數量多出一倍左右。
var options = selectSrc.getElementsByTagName("option");
var optLength = options.length; // 先把長度存起來
/* 也不能在迴圈條件裡寫 options.length:
appendChild 執行後會讓 options.length 減一,迴圈會提早結束。 */
for (var i = 0; i < optLength; i++) {
var option = options[0]; // 每次都取第 0 個(取了之後它就被搬走)
selectDes.appendChild(option);
}
selectSrc.options.length = 0; // 保險起見再清一次
}
function selectToRightAll() {
selAll(document.getElementById("select1"), document.getElementById("select2"));
}
function selectToLeftAll() {
selAll(document.getElementById("select2"), document.getElementById("select1"));
}
</script>
介面用 float 排成左右兩欄:
<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>
原始碼的註解誠實記錄了兩個 debug 過程,這正是最值得學習的部分。
第一個坑:selectSrc.childNodes.length 居然是 10,實際上只有 5 個 option。原因是標籤之間的換行與縮排都被解析成文字節點, interleaved 在 option 之間。要只取元素節點,該用 getElementsByTagName("option") 或 children。
第二個坑:迴圈條件裡不能直接寫 options.length。因為每次 selectDes.appendChild(option) 把節點搬走後,options 集合的長度會同步減少,導致 i 追上長度而提早結束,結果只搬了一半。解法有兩個:先把長度存進變數(如本例),或反覆取 index 0 直到集合空為止。
這兩個坑背後是同一個道理:操作 live collection 時,迴圈邊界必須先固定,或改用倒序/反覆取首元素的方式。這條規則適用於所有 DOM 集合的增刪場景。