gpt4 book ai didi

jquery - 使用 JQuery 将所选项目从一个组合框添加到另一个组合框

转载 作者:行者123 更新时间:2023-12-01 02:24:01 24 4
gpt4 key购买 nike

我正在尝试找到将所选项目从一个组合框添加到另一个组合框的最佳方法。诀窍是我只想将尚不存在的项目添加到目标列表中。目前我使用的流程相当丑陋,并且无法按我的预期工作。

$('#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 方法更多地充当移动而不是添加。然后是删除重复项的问题,这在本例中是有效的,但我忍不住认为有更好的方法。

任何帮助将不胜感激。

谢谢

最佳答案

使用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/

<小时/>

<强> clone()

Create a deep copy of the set of matched elements.

<强> grep()

Finds the elements of an array which satisfy a filter function. The original array is not affected.

关于jquery - 使用 JQuery 将所选项目从一个组合框添加到另一个组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7570629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com