使用 JQuery 将选定的项目从一个组合框添加到另一个组合框
我正在尝试找到将所选项目从一个组合框添加到另一个组合框的最佳方法。诀窍是我只想将尚不存在的项目添加到目标列表中。目前我使用的过程相当丑陋,并且不能按我的预期工作。
$('#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 方法更多地充当移动而不是添加。然后是删除重复项的问题,这在本例中是有效的,但我忍不住认为有更好的方法。
任何帮助将不胜感激。
谢谢,
I'm trying to find the best way to add selected items from one combobox to another. The trick is I only want to add items to the destination list that don't already exist. Currently the process I use is rather ugly and does not work as I would expect.
$('#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;
});
});
The problem I'm having is that the appendTo method acts as more of a move rather than an add. Then there's the problem of removing the duplicates, which works in this this example, but I can't help but think there's a better way.
Any assistance would be greatly appreciated.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
clone()
和grep()
你可以轻松实现这一点。首先克隆从源中选择的选项,然后使用grep可以过滤掉目标列表中已有的项目。工作示例: http://jsfiddle.net/hunter/4GK9A/
clone()
grep()
using
clone()
andgrep()
you can achieve this easily. First clone the options that are selected from the source and then using grep you can filter out the items that are already in the destination list.Working Example: http://jsfiddle.net/hunter/4GK9A/
clone()
grep()
我认为您想要的是将“克隆”与附加结合使用:
http://api.jquery.com/克隆/
I think what you want is to use "clone" in conjunction with append:
http://api.jquery.com/clone/
你可以像这样使用clone():
You could use clone() like this:
您只需在目标列表中搜索包含的值即可。 http://jsfiddle.net/EHqem/
You can just search the destination list for the containing value. http://jsfiddle.net/EHqem/