从选择框中删除重复的条目 [英] Delete duplicate entries from a select box

查看:100
本文介绍了从选择框中删除重复的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用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); 
});

在这里尝试一下,这是一个简单的方法,我们只是保留一个发现值的数组,如果我们没有找到值,将它添加到数组( .push() ),如果 em>发现了这个值,这是我们之前发现的一个重复, .remove()
$ b

这只抓取< select> 一次,最小化DOM遍历这是一个比数组操作更昂贵的 。我们还使用 $。inArray() 而不是 .indexOf(),所以这个在IE中可以正常工作。




如果您想要效率较低但较短的解决方案(仅用于说明,请使用第一种方法!):

  $('select option')。each(function(){
$(this).prevAll('option [value =''+ this.value +'')')。remove();
});

你可以在这里测试,这将删除具有相同值的所有兄弟,但它比第一个方法(DOM Traversal昂贵,并且多个选择器引擎在这里调用更多)要昂贵得多。我们使用 .prevAll() ,因为你不能删除 .siblings() .each() 中,它因为它预计下一个孩子会导致循环出现一些错误。


How would I, using jQuery, remove the dups

        <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>

解决方案

You can do it like this:

var found = [];
$("select option").each(function() {
  if($.inArray(this.value, found) != -1) $(this).remove();
  found.push(this.value);
});

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 (.push()), if we have found the value, this one's a dupe we found earlier, .remove() it.

This only crawls the <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.


If you want a less efficient but shorter solution (just for illustration, use the first method!):

$('select option').each(function() {
  $(this).prevAll('option[value="' + this.value + '"]').remove();
});

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 .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. ​

这篇关于从选择框中删除重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆