jQuery 从选择下拉列表中过滤重复选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1875607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter duplicate options from select dropdown
提问by afewscoops
I have a dropdown selector generated from a list and want to filter the options to remove the duplicate entries. e.g. I want to filter ...
我有一个从列表生成的下拉选择器,并希望过滤选项以删除重复条目。例如我想过滤...
<select name="company">
<option "1">Microsoft</option>
<option "2">Microsoft</option>
<option "3">Microsoft</option>
<option "4">Microsoft</option>
<option "5">Apple</option>
<option "6">Apple</option>
<option "7">Google</option>
</select>
... down to present the user with something like...
...向下向用户展示类似...
<select name="company">
<option "1">Microsoft</option>
<option "5">Apple</option>
<option "7">Google</option>
</select>
(The data comes from a Sharepoint Lookup on another list and I'm thinking I can use jquery to keep only the unique options without having to go into the guts of what's going on.) Can I remove options like this? Thanks.
(数据来自另一个列表上的 Sharepoint 查找,我想我可以使用 jquery 只保留唯一选项,而不必深入了解正在发生的事情。)我可以删除这样的选项吗?谢谢。
回答by Greg Campbell
You can do it with a simple loop - there may be a cleverer way to handle this with jQuery selectors that I'm not seeing, though. The following should work:
你可以用一个简单的循环来完成——不过,可能有一种更聪明的方法来处理我没有看到的 jQuery 选择器。以下应该工作:
var usedNames = {};
$("select[name='company'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
Edit:Here's a functional-style one-liner that does it with the help of the excellent Underscore.js, although the previous version is almost certainly more efficient:
编辑:这是一个函数式的单行代码,它在优秀的Underscore.js的帮助下完成,尽管以前的版本几乎可以肯定效率更高:
_.each(_.uniq(_.pluck($("select[name='company'] > option").get(), 'text')), function(name) { $("select[name='company'] > option:contains(" + name + ")").not(":first").remove(); });
回答by Justin Swartsel
You can do something like this:
你可以这样做:
var previousOption;
$('select[name=company] option').each(function() {
if (this.text == previousOption) $(this).remove();
previousOption= this.text;
});
回答by Namwar Rizvi
You can try the following code, it will remove the duplicates regardless of their position. Here #targetSelect is your target Dropdown
您可以尝试以下代码,无论它们的位置如何,它都会删除重复项。这里#targetSelect 是你的目标下拉菜单
var a = new Array();
$(#targetSelect).children("option").each(function(x){
test = false;
b = a[x] = $(this).text();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
});