jquery - 使用 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链接。
解决方案
我将选定的项目存储在某处。为了检查目的地中的现有项目,我将每个选定的项目逐一检查。我将在代码内部进行解释以使其更容易。
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);
}
}
}
推荐阅读
- java - Java - 将 XML 文件转换为 Docx 文件
- vb.net - 检查外部程序是否是活动窗口
- javascript - 如何在 odoo 11.0 中添加新的 javascript 文件并在加载 web/登录时调用脚本?
- cuda - 在 n×1 向量中的 m×n 矩阵的 Cuda 乘法
- command - 使用 adobe illustrator 命令行或批量转换将 .ai 转换为 .svg 文件
- javascript - 使用 AngularJS 1.5 转换组件内的所有子元素
- sql - 重复值插入,当使用可序列化的隔离级别时
- android - HttpConnection 错误 500
- python - 数组 fileld postgres 中最常见的词
- java - 运行时 exec 不显示结果