Javascript 从html元素中删除重复项
什么是最好的办法,以消除重复的葡萄从这个?有很多方法可以从简单数组中删除重复项,但这将是一个包含html元素的数组Javascript 从html元素中删除重复项,javascript,jquery,Javascript,Jquery,什么是最好的办法,以消除重复的葡萄从这个?有很多方法可以从简单数组中删除重复项,但这将是一个包含html元素的数组 <div class="fruit"> grapes </div> <div class="fruit"> bananas </div> <div class="fruit"> grapes </div> :has需要一个元素选择器,而:contains需要一
<div class="fruit">
grapes
</div>
<div class="fruit">
bananas
</div>
<div class="fruit">
grapes
</div>
:has
需要一个元素选择器,而:contains
需要一个字符串
看
因此,这应该可以做到:
$('.fruit').each(function () {
$('.fruit:contains("' + $(this).text() + '"):gt(0)').remove();
});
小提琴:试试看
var obj = {};
$('.fruit').each(function(){
var text = $.trim($(this).text());
if(obj[text]){
$(this).remove();
} else {
obj[text] = true;
}
})
演示:这是这把小提琴的工作原理:- 假设您只希望删除其中一个副本 使用,与上面的答案类似,但实现略有不同
$($("div:contains('grapes')")[0]).remove();
-这也可能对您有用
var uniqueFruits = [];
$(".fruit").each(function(i,e){
var thisFruit = $.trim($(e).text());
if(uniqueFruits.indexOf(thisFruit) == -1)
uniqueFruits.push(thisFruit);
else
$(e).remove();
});
jsiddle此处:
没错,我也想知道。我认为小提琴很好,不知道为什么这么做。
$($("div:contains('grapes')")[0]).remove();
var uniqueFruits = [];
$(".fruit").each(function(i,e){
var thisFruit = $.trim($(e).text());
if(uniqueFruits.indexOf(thisFruit) == -1)
uniqueFruits.push(thisFruit);
else
$(e).remove();
});
var found = {};
var $unique_fruits = $('.fruit').filter(function(){
var data = this.innerHTML.trim();
if(!found.hasOwnProperty(data)) return found[data] = true;
});