【问题标题】:Display unique element using jquery使用 jquery 显示唯一元素
【发布时间】:2017-04-03 12:43:10
【问题描述】:

我有动态生成的元素,想按唯一的 id 排序,即如果 id 相同三次只显示一个。

<li id="721" class="mylist"  />        
<li id="721" class="mylist"  />     
<li id="721" class="mylist"  />     

<li id="722" class="mylist"  />        
<li id="722" class="mylist" />     

<li id="723" class="mylist"  />        
<li id="723"  />

最后我想得到

<li id="721" class="mylist"  /> 
<li id="722" class="mylist"  />        
<li id="723" class="mylist"  />  

我正在尝试 jquery 脚本

var arr = [];
$.each( $('.mylist'), function(){

  var id= this.id;
  if( $.inArray( id, arr ) < 0 ){
     $this.hide(); 
  }

});      

【问题讨论】:

  • 你要求做unique,那么li list的值呢?它有 A,I,R
  • id 必须默认是唯一的。如果您要创建具有相同 ID 的元素,则需要在执行其他任何操作之前重新设计代码。
  • 该值不需要,我们可以去掉它
  • 您的“预期”结果不是唯一的列表。也许您可以改写标题以反映您想要的内容。

标签: jquery arrays sorting element


【解决方案1】:

试试这个,

arr = [];
n = 0;
$(".mylist").each(function() {
  if (n == 0 || n != $(this).attr("id")) {
    n = $(this).attr("id");
  } else {
    $(this).hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="721" class="mylist">1</li>
<li id="721" class="mylist">2</li>
<li id="721" class="mylist">3</li>

<li id="722" class="mylist">4</li>
<li id="722" class="mylist">5</li>

<li id="723" class="mylist">6</li>
<li id="723" class="mylist">7</li>

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    正如@mpf82 提到的,您的所有 ID 都必须是唯一的。您可以将您的 ID 转移到数据属性。

    我用一些 cmets 做了一个快速的 codepen 来解释我做了什么:https://codepen.io/frankbiemans/pen/xqBxdJ

    // This var will hold all the unique data ids
    var uids = [];
    
    // Collect all different ID's used
    $.each( $('.mylist li'), function(){
      // Get the data-id attribute
      var id = $(this).data('id');
    
      // Only add if the ID is unique
      if($.inArray(id, uids) === -1) {
        uids.push(id);
      }
    });
    
    // For each ID in array...
    uids.forEach(function(id, index, object) {
      // If there is more then one li with this ID #...
      if($('li[data-id="' + id + '"]').length > 1){
    
        // get all items with this id
        var items = $('li[data-id="' + id + '"]');
    
        // Get totel number of items with this id
        var numItems = $('li[data-id="' + id + '"]').length;
    
        // Create a random number between 0 and the number of items with this id
        var rand = Math.floor(Math.random()* numItems);
    
        // Make all inactive...
        $('li[data-id="' + id + '"]').addClass('inactive');
    
        // ...except one 
        $(items[rand]).removeClass('inactive');
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 2017-03-27
      相关资源
      最近更新 更多