我有两个选择列表,您可以在它们之间移动选定的选项。您还可以在右侧列表中上下移动选项。
当我将选项移回左侧列表时,我希望它们在列表顺序中保留其原始位置,即使列表缺少一些原始选项。这仅是为了使列表对用户更方便。
我目前正在使用原始选择列表 onload 定义一个数组。
实现这一点的最佳方法是什么?
我有两个选择列表,您可以在它们之间移动选定的选项。您还可以在右侧列表中上下移动选项。
当我将选项移回左侧列表时,我希望它们在列表顺序中保留其原始位置,即使列表缺少一些原始选项。这仅是为了使列表对用户更方便。
我目前正在使用原始选择列表 onload 定义一个数组。
实现这一点的最佳方法是什么?
您可以将原始顺序存储在一个数组中,并在插入时确定数组中要插入的元素之前的最新元素是什么,并且与选择列表中的当前元素相匹配。然后在之后插入。
更好的解决方案是只存储整个旧数组并在每次插入时重新填充所需的元素,如下所示(警告:代码未测试)
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]);
}
}
}
我会为项目分配升序值,以便您可以将项目重新插入正确的位置。无论它在哪个列表中,分配的值都与项目保持一致。