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://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 に答える
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 に答える