「穿梭框」是很常見的互動元件,例如把可選項從左側移到右側。下面整理出四個函數,分別負責把選中項、全部項向左或向右移動,並示範如何綁定雙擊事件。
function moveToRight(select1, select2){ // 把選中的移動到右邊
$('#'+select1+' option:selected').each(function(){
$("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>").appendTo("#"+select2);
$(this).remove();
});
}
function moveAllToRight(select1, select2){ // 把全部移動到右邊
$('#'+select1+' option').each(function(){
$("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>").appendTo("#"+select2);
$(this).remove();
});
}
function moveToLeft(select1, select2){ // 把選中的移動到左邊
$('#'+select2+' option:selected').each(function(){
$("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>").appendTo("#"+select1);
$(this).remove();
});
}
function moveAllToLeft(select1, select2){ // 把全部移動到左邊
$('#'+select2+' option').each(function(){
$("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>").appendTo("#"+select1);
$(this).remove();
});
}
若想雙擊某個 option 就把值傳到另一個 select,只要為下拉框綁定 dblclick 事件即可:
$('#sel2').bind('dblclick', function(){ // 給下拉框綁定雙擊事件
moveToRight('sel2', 'sel3');
});
$('#sel3').bind('dblclick', function(){
moveToLeft('sel2', 'sel3');
});
每個函數的核心都是遍歷目標 option,建立新的 option 元素附加到對側,再把原元素移除,如此一來一往就完成了穿梭效果。