2017-04-03 179 views
0

我有動態生成的元素,並希望通過id唯一進行排序,即如果id相同,則三次只顯示一個。使用jquery顯示獨特元素

<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(); 
    } 

});  
+0

你問做獨樹一幟,約李列表的價值是什麼?它有A,I,R –

+0

默認情況下,''id'' **必須是唯一的。如果您使用相同的ID創建元素,則需要在做其他任何事情之前重新設計您的代碼。 –

+0

可能重複的[jQuery選擇除第一個以外](http://stackoverflow.com/questions/2259393/jquery-select-all-except-first) –

回答

0

試試這個月底,

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>

我希望這會有所幫助。

0

作爲@ mpf82提到所有你的ID必須是唯一的。您可以將您的ID轉移到數據屬性。

我做了一個快速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'); 
    } 
});