从选择下拉列表中过滤重复选项 [英] Filter duplicate options from select dropdown
问题描述
我有一个从列表生成的下拉选择器,我想过滤选项以删除重复条目.例如我想过滤...
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>
(数据来自另一个列表上的 Sharepoint Lookup,我想我可以使用 jquery 只保留唯一选项,而不必深入了解正在发生的事情.)我可以删除这样的选项吗?谢谢.
(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.
推荐答案
你可以用一个简单的循环来完成——不过,可能有一种更聪明的方法来处理我没有看到的 jQuery 选择器.以下应该有效:
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:
var usedNames = {};
$("select[name='company'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
这是一个函数式的单行代码,它在优秀的Underscore.js,虽然以前的版本几乎可以肯定效率更高:
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:
_.each(_.uniq(_.pluck($("select[name='company'] > option").get(), 'text')), function(name) { $("select[name='company'] > option:contains(" + name + ")").not(":first").remove(); });
这篇关于从选择下拉列表中过滤重复选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!