2

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

$('#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方法更像是移动而不是添加。然后是删除重复项的问题,这在此示例中有效,但我不禁想到有更好的方法。

任何帮助将不胜感激。

谢谢,

4

4 回答 4

5

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

工作示例:http: //jsfiddle.net/hunter/4GK9A/


克隆()

创建匹配元素集的深层副本。

grep()

查找满足过滤器函数的数组元素。原始数组不受影响。

于 2011-09-27T14:26:12.767 回答
1

我认为您想要的是将“克隆”与附加一起使用:

http://api.jquery.com/clone/

于 2011-09-27T14:23:21.517 回答
1

您可以像这样使用 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;
    });
});
于 2011-09-27T14:27:23.423 回答
1

您可以在目标列表中搜索包含的值。http://jsfiddle.net/EHqem/

$('#addSelectedButton').click(function() {
    $('#sourceList option:selected').each(function(i, el) {
        if ($('#destinationList option[value='+$(el).val()+']').length === 0) {
           $('#destinationList').append($(el).clone());
        }
    });
});
于 2011-09-27T14:38:05.197 回答