代码之家  ›  专栏  ›  技术社区  ›  Jamie Taylor

在jquery中隐藏重复的div

  •  1
  • Jamie Taylor  · 技术社区  · 14 年前

    <div><p class="locid">2<p></div>
    <div><p class="locid">1<p></div>
    <div><p class="locid">2<p></div>
    <div><p class="locid">3<p></div>
    <div><p class="locid">4<p></div>
    

    我需要做的是隐藏该层的第二个引用,使其显示如下

    <div><p class="locid">2<p></div>
    <div><p class="locid">1<p></div>
    <div><p class="locid">3<p></div>
    <div><p class="locid">4<p></div>
    

    有什么想法吗?

    谢谢

    5 回复  |  直到 14 年前
        1
  •  1
  •   karim79    14 年前
    // get a collection of p's matching some value
    $("p.locid").filter(function() {
        return $(this).text() == '2';
    
    // hide the (div) parent of the second match
    }).eq(1).parent().hide();
    

    演示: http://jsfiddle.net/WjgxQ/

        2
  •  1
  •   simplyharsh    14 年前

    var a = new Array();
    $('p.locid').each(function(){
        text = $(this).text();
        if($.inArray(text, a)){
            $(this).closest('div').hide();
        }else{
            a.push(text);
        }
    });
    
        3
  •  1
  •   Tim Cooper    13 年前
        4
  •  0
  •   Sarfraz    14 年前

    试试这个:

    var arr = new array();
    
    $('.locid').each(function(){
      if ($.inArray($(this).text(), arr) !== -1){
         $(this).closest('div').remove();
      }
      else{
        arr[] = $(this).text();
      }
    });
    
        5
  •  0
  •   amof    12 年前

    这样做有效:

    var a = new Array();
    
    $('p').each(function(index) {
        text = $(this).text();
        if($.inArray(text, a)!=-1){
            $(this).closest('p').hide();
        }else{
            a.push(text);
        }
    });
    

    http://jsfiddle.net/WjgxQ/59/