如何删除具有相同值的重复下拉选项元素
如何删除重复值 – >下拉选项元素?
我有以下HTML:
All Servers http://smiles.com http://3smiles.com http://desk.com http://france24.com
从上面我必须删除重复值com
和in
,所以我的预期输出应该是:
All Servers http://smiles.com http://3smiles.com
如何使用jQuery做到这一点?
使用.siblings()
(定位兄弟option
元素)和属性等于选择器[attr=""]
$(".select option").val(function(idx, val) { $(this).siblings('[value="'+ val +'"]').remove(); });
正确的解决方案是不允许服务器具有重复值….
尝试
var map = {}; $('select option').each(function () { if (map[this.value]) { $(this).remove() } map[this.value] = true; })
演示: 小提琴
用这个 :
$(document).ready(function () { var usedNames = {}; $("select > option").each(function () { if (usedNames[this.value]) { $(this).remove(); } else { usedNames[this.value] = this.text; } }); });
这里演示: http : //jsfiddle.net/aelor/aspMT/
HTML
jQuery的
var seen = {}; jQuery('.something').children().each(function() { var txt = jQuery(this).attr('value'); if (seen[txt]) { jQuery(this).remove(); } else { seen[txt] = true; } });
演示
这个怎么样。
演示: http : //jsfiddle.net/naokiota/yayTm/2/
var exist = {}; $('select > option').each(function() { if (exist[$(this).val()]){ $(this).remove(); }else{ exist[$(this).val()] = true; } });
希望这可以帮助。
未经测试,但这样的事情应该有效
var values = new Array(); $('#YourSelect').children('option').each(function() { var text = $(this).text(); if (values.indexOf(text) === -1) { values.push(text); } else { // Its a duplicate $(this).remove() } }