使用JQuery将选定项从一个组合框添加到另一个组合框

使用JQuery将选定项从一个组合框添加到另一个组合框,jquery,appendto,Jquery,Appendto,我正试图找到将选定项目从一个组合框添加到另一个组合框的最佳方法。诀窍是我只想将不存在的项目添加到目标列表中。目前,我使用的过程相当难看,并不像我预期的那样有效 $('#addSelectedButton').click(function() { var previousOption; $('#sourceList option:selected').appendTo('#destinationList'); $('select[name=destinationList]

我正试图找到将选定项目从一个组合框添加到另一个组合框的最佳方法。诀窍是我只想将不存在的项目添加到目标列表中。目前,我使用的过程相当难看,并不像我预期的那样有效

$('#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;
    });
});
我遇到的问题是,appendTo方法更像是一种移动,而不是添加。然后是删除重复项的问题,在本例中是有效的,但我忍不住认为有更好的方法

如蒙协助,将不胜感激


谢谢,

我认为您需要将“克隆”与append结合使用:

使用
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);
});

工作示例:


创建匹配元素集的深度副本

查找满足筛选函数的数组元素。原始阵列不受影响

您可以像这样使用clone():

$('#addSelectedButton').click(function() {
    var previousOption;
    var clone =  $('#sourceList option:selected').clone();
    clone.appendTo('#destinationList');
    $('select[name=destinationList] option').each(function () {
        if (this.text == previousOption) $(this).remove();
        previousOption = this.text;
    });
});

您只需在目标列表中搜索包含的值


你也可以添加html代码段。太棒了!像冠军一样工作!grep的好用法!忘了那个。
$('#addSelectedButton').click(function() {
    $('#sourceList option:selected').each(function(i, el) {
        if ($('#destinationList option[value='+$(el).val()+']').length === 0) {
           $('#destinationList').append($(el).clone());
        }
    });
});