我正在尝试找到将所选项目从一个组合框添加到另一个组合框的最佳方法.诀窍是我只想将项目添加到目标列表中但尚不存在.目前我使用的过程相当丑陋,不能像我期望的那样工作.
$('#addSelectedButton').click(function() {
var previousOption;
$('#sourceList option:selected').appendTo('#destinationList');
$('select[name=destinationList] option').each(function () {
if (this.text == previousOption) $(this).remove();
previousOption = this.text;
});
});
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是appendTo方法更多的是移动而不是添加.然后就是删除重复项的问题,这在本例中有效,但我不禁想到有更好的方法.
任何帮助将不胜感激.
谢谢,
使用clone(),grep()你可以轻松实现这一目标.首先克隆从源中选择的选项,然后使用grep,您可以筛选出目标列表中已有的项目.
$('#addSelectedButton').click(function() {
// select this once into a variable to minimize re-selecting
var $destinationList = $('#destinationList');
// clone all selected items
var $items = $.grep($('#sourceList option:selected').clone(), function(v){
// if the item does not exist return true which includes it in the new array
return $destinationList.find("option[value='" + $(v).val() + "']").length == 0;
});
// append the collection to the destination list
$destinationList.append($items);
});
Run Code Online (Sandbox Code Playgroud)
工作示例: http ://jsfiddle.net/hunter/4GK9A/
创建匹配元素集的深层副本.
查找满足过滤函数的数组元素.原始数组不受影响.