效果如下:
几个注意地方:
1.多选下拉框需要添加 multiple
2.获取选中的元素KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲id option:selec…(#id option:not(:selected))
下面是代码的各个部分实现, 方便引用,最后是总体代码,方便理解
添加选中到右边:
// 添加选中到右边
$('#add').click(()=>{let $options = $('#select1 option:selected')let $remove = $options.remove();$('#select2').append($remove);
})
添加未选到右边:
// 添加未选到右边
$('#add_not').click(()=>{let $options = $('#select1 option:not(:selected)')let $remove = $options.remove();$('#select2').append($remove);
})
全部添加到右边:
// 全部添加到右边
$('#add_all').click(()=>{let $remove = $('#select1 option').remove()$('#select2').append($remove);
})
整体代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>.content{display: inline-block;margin-left:15px;}div span{display: block;margin-left:-15px;}#add,#add_all,#add_not,#remove,#remove_all,#remove_not{cursor: pointer;}#select1{width: 100px;height: 160px;}#select2{width:100px;height:160px;}</style>
</head>
<body><div class="content"><select multiple id="select1"><option value="1">选项1</option><option value="2">选项2</option><option value="3">选项3</option><option value="4">选项4</option><option value="5">选项5</option><option value="6">选项6</option><option value="7">选项7</option><option value="8">选项8</option></select><div><span id="add">选中添加到右边>></span><span id="add_not">添加未选到右边>></span><span id="add_all">全部添加到右边>></span></div>
</div>
<div class="content" style="margin-left:30px;"><select multiple id="select2" ></select><div><span id="remove"><<选中删除到左边</span><span id="remove_not"><<添加未选到左边</span><span id="remove_all"><<全部删除到左边</span></div>
</div><script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
$(function(){// 添加选中到右边$('#add').click(()=>{let $options = $('#select1 option:selected')let $remove = $options.remove();$('#select2').append($remove);})// 添加未选到右边$('#add_not').click(()=>{let $options = $('#select1 option:not(:selected)')let $remove = $options.remove();$('#select2').append($remove);})// 全部添加到右边$('#add_all').click(()=>{let $remove = $('#select1 option').remove()$('#select2').append($remove);})// 删除选中到左边$('#remove').click(()=>{let $options = $('#select2 option:selected')let $remove = $options.remove();$('#select1').append($remove);})// 删除未选到左边$('#remove_not').click(()=>{let $options = $('#select2 option:not(:selected)')let $remove = $options.remove();$('#select1').append($remove);})// 全部删除到左边$('#remove_all').click(()=>{let $remove = $('#select2 option')$('#select1').append($remove);})
})
</script></body>
</html>
参考《锋利的jquery》P149~P151