从选择框中删除重复的条目 [英] Delete duplicate entries from a select box
问题描述
我如何使用jQuery删除dups
< option value =English> English<选项>
< option value =English>英语< / option>
< option value =English>英语< / option>
< option value =Geology> Geology< / option>
< option value =Geology> Geology< / option>
< option value =信息技术>信息技术< / option>
< option value =Music>音乐< / option>
< option value =Music>音乐< / option>
< option value =动物学>动物学< / option>
您可以这样做:
var found = []; $($。inArray(this.value,found)!= -1)$(this).remove(); $ b(select option)。 $ b found.push(this.value);
});
在这里尝试一下,这是一个简单的方法,我们只是保留一个发现值的数组,如果我们没有找到值,将它添加到数组( 这只抓取 如果您想要效率较低但较短的解决方案(仅用于说明,请使用第一种方法!): 你可以在这里测试,这将删除具有相同值的所有兄弟,但它比第一个方法(DOM Traversal昂贵,并且多个选择器引擎在这里调用更多)要昂贵得多。我们使用 How would I, using jQuery, remove the dups
You can do it like this: Give it a try here, it's a simple approach, we're just keeping an array of found values, if we haven't found the value, add it to the array ( This only crawls the If you want a less efficient but shorter solution (just for illustration, use the first method!): You can test it here, this removes all siblings with the same value, but it's much more expensive than the first method (DOM Traversal is expensive, and multiple selector engine calls here, many more). We're using 这篇关于从选择框中删除重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! .push()
),如果 em>发现了这个值,这是我们之前发现的一个重复, .remove()
$ b < select>
一次,最小化DOM遍历这是一个比数组操作更昂贵的 。我们还使用 $。inArray()
而不是 .indexOf()
,所以这个在IE中可以正常工作。
$('select option')。each(function(){
$(this).prevAll('option [value =''+ this.value +'')')。remove();
});
.prevAll()
,因为你不能删除 .siblings()
在 .each()
中,它因为它预计下一个孩子会导致循环出现一些错误。
<option value="English">English</option>
<option value="English">English</option>
<option value="English">English</option>
<option value="Geology">Geology</option>
<option value="Geology">Geology</option>
<option value="Information Technology">Information Technology</option>
<option value="Music">Music</option>
<option value="Music">Music</option>
<option value="Zoology">Zoology</option>
var found = [];
$("select option").each(function() {
if($.inArray(this.value, found) != -1) $(this).remove();
found.push(this.value);
});
.push()
), if we have found the value, this one's a dupe we found earlier, .remove()
it.<select>
once, minimizing DOM traversal which is a lot more expensive than array operations. Also we're using $.inArray()
instead of .indexOf()
so this works properly in IE.
$('select option').each(function() {
$(this).prevAll('option[value="' + this.value + '"]').remove();
});
.prevAll()
because you can't just remove .siblings()
inside an .each()
, it'll cause some errors with the loop since it expected the next child.