2010-04-20 17 views
4

我有兩個選擇列表,您可以在其中移動選定的選項。您也可以在右側列表中上下移動選項。如何將(不完整)選擇列表的順序恢復到其原始順序?

當我將選項移回左側列表時,我希望它們按列表順序保留其原始位置,即使列表中缺少一些原始選項。這僅僅是爲了使用戶更方便列表的目的。

我目前正在定義一個原始選擇列表onload的數組。

什麼是最好的實施方式?

回答

5

您可以將原始順序存儲在數組中,並且在返回時確定數組中最後一個要插入的元素與AND匹配選擇列表中的當前內容。然後插入。

更好的解決方案是隻存儲舊陣列整體並在每次插入與所需元素如下(警告:未測試代碼)重新填充

function init(selectId) { 
    var s = document.getElementById(selectId); 
    select_defaults[selectId] = []; 
    select_on[selectId] = []; 
    for (var i = 0; i < s.options.length; i++) { 
     select_defaults[selectId][i] = s.options[i]; 
     select_on[selectId][i] = 1; 
     var value = list.options[i].value; 
     select_map_values[selectId][value] = i if you wish to add/remove by value. 
     var id = list.options[i].id; // if ID is defined for all options 
     select_map_ids[selectId][id] = i if you wish to add/remove by id. 
    } 
} 

function switch(selectId, num, id, value, to_add) { // You can pass number, value or id 
    if (num == null) { 
     if (id != null) { 
      num = select_map_ids[selectId][id]; // check if empty? 
     } else { 
      num = select_map_values[selectId][value]; // check if empty? 
     } 
    } 
    var old = select_on[selectId][num]; 
    var newOption = (to_add) : 1 : 0; 
    if (old != newOption) { 
     select_on[selectId][num] = newOption; 
     redraw(selectId); 
    } 
} 

function add(selectId, num, id, value) { 
    switch(selectId, num, id, value, 1); 
} 

function remove(selectId, num, id, value) { 
    switch(selectId, num, id, value, 0); 
} 

function redraw(selectId) { 
    var s = document.getElementById(selectId); 
    s.options.length = 0; // empty out 
    for (var i = 0; i < select_on[selectId].length; i++) { 
     // can use global "initial_length" stored in init() instead of select_on[selectId].length 
     if (select_on[selectId][i] == 1) { 
      s.options.push(select_defaults[selectId][i]); 
     } 
    } 
} 
+0

感謝。我使用了類似的技術。 – 2010-04-21 02:28:46

0

我會爲項目分配升序值,以便您可以將項目插回到正確的位置。分配的值與該項目保持一致,不管它在哪個列表中。