首页 > 解决方案 > 使用 jQuery 仅将唯一项目从一个多选列表移动到另一个

问题描述

这是我的选择框...

<select id="selectOne" multiple style="height: 150px">
 <option>March 2018</option>
 <option>May 2018</option>
 <option>January 2019</option>
 <option>August 2020</option>
</select>

<button type='button' id="btnRight"> >> </button>
<button type='button' id="btnLeft"> << </button>

<select id="selectTwo" multiple style="height: 150px">
 <option>Anaconda</option>
 <option>Daniel</option>
 <option>Jack</option>
 <option>March 2018</option>
</select>

这是我的jQuery

$(function() {
 function moveItems(origin, dest) {
  $(origin).find(':selected').appendTo(dest);
 }

function moveAllItems(origin, dest) {
 $(origin).children().appendTo(dest);
}

$('#btnLeft').click(function() {
 moveItems('#selectTwo', '#selectOne');
 });

 $('#btnRight').on('click', function() {
   moveItems('#selectOne', '#selectTwo');
 });

});

我可以移动选择选项,但如果右选择框中存在任何选项,我只想移动唯一选项,然后保留移动数据并删除现有数据。

这是jsfiddle链接。

https://jsfiddle.net/uthpal/g60sertc/

标签: jqueryduplicatesmove

解决方案


我将选定的项目存储在某处。为了检查目的地中的现有项目,我将每个选定的项目逐一检查。我将在代码内部进行解释以使其更容易。

function moveItems(origin, dest) {
    var o = $(origin).find(':selected');
    for (var i = 0; i < o.length; i++) {
        for (var j = 0; j < $(dest).children().length; j++) {
            if ($(dest).children()[j].text == o[i].text){
                break; // stop looping once the selected item is found in destination.
            }
        }
        var temp = $(dest).children().length; // keep the original destination size
        $(dest)[0].appendChild(o[i]);
        if (j != temp) { // remove the duplicate item in destination 
            $(dest)[0].removeChild($(dest)[0].lastChild);
        }
    }
}

推荐阅读