jQuery代码删除具有相同内容的所有跨度但保留一个

时间:2010-04-05 01:08:53

标签: javascript jquery

说我有以下html:

<span class="fruit">Apple</span>
<span class="fruit">banana</span>
<span class="fruit">Apple</span>
<span class="fruit">Apple</span>
<span class="fruit">orange</span>

我尝试了不同的方法,但它没有用,我想要一个jQuery代码删除所有(.fruit)跨度相同的内容,但保留一个(如果可能的话,第一个),所以我将最终得到以下内容: / p>

<span class="fruit">Apple</span>
<span class="fruit">banana</span>
<span class="fruit">orange</span>

谢谢

4 个答案:

答案 0 :(得分:8)

 $("span.fruit:contains(Apple):not(:first)").remove();

答案 1 :(得分:2)

$('span.fruit').each(function(){
  return $('span.fruit:contains('+$(this).text()+'):not(:first)').remove();
})

答案 2 :(得分:1)

var temp = array[];

$(".fruit").each(function(i) {
    var html = $($this).html();
    if($.inArray(html, temp)) {
        $($this).remove();
    }
    else {
        temp.push(html);
    }

});

答案 3 :(得分:0)

temp = $('span:first').clone(true);
//remove all the span
$().html();
$().append(temp);