使用jquery显示独特元素
问题描述:
我有动态生成的元素,并希望通过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();
}
});
答
试试这个月底,
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>
我希望这会有所帮助。
答
作为@ 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');
}
});
你问做独树一帜,约李列表的价值是什么?它有A,I,R –
默认情况下,''id'' **必须是唯一的。如果您使用相同的ID创建元素,则需要在做其他任何事情之前重新设计您的代码。 –
可能重复的[jQuery选择除第一个以外](http://stackoverflow.com/questions/2259393/jquery-select-all-except-first) –