[英]Find elements with one element of array
I have a list of elements, each one with one numeric ID and I'm creating a filter to group them 我有一个元素列表,每个元素都有一个数字ID,我正在创建一个过滤器以将它们分组
One of the filters has to take the elements that have an ID specified in the array 筛选器之一必须采用在数组中指定了ID的元素
Such as: 如:
var orgsID = [4002,4037];
//Show if it has one of the IDs from the array
$('.event_item[data-id='+orgsID+']').addClass('show-item all');
And then go one by one checking whether the LI has that ID. 然后一个接一个地检查LI是否具有该ID。 If so, show it 如果是这样,请显示
This is the filter: 这是过滤器:
<ul id="e-filters">
<li class="active" id="all">All</li>
<li id="49504">SU Sports Events</li>
<li id="4002" class="sportsID">Sports Clubs Events</li> <!-- Get elements from array -->
</ul>
This is the list: 这是清单:
<div id="e-list">
<div class="event_item" data-id="4219"></div>
<div class="event_item" data-id="4002"></div>
<div class="event_item" data-id="5146"></div>
<div class="event_item" data-id="4037"></div>
</div>
You can do it like this: 您可以这样做:
$('.event_item').filter(function() {
return jQuery.inArray($(this).data("id"), orgsID) > -1;
}).addClass('show-item all');
Demo 演示
var orgsID = [4002, 4037]; $('.event_item').filter(function() { return jQuery.inArray($(this).data("id"), orgsID) > -1; }).addClass('show-item all');
.show-item{ color: blue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="e-list"> <div class="event_item" data-id="4219">4219</div> <div class="event_item" data-id="4002">4002</div> <div class="event_item" data-id="5146">5146</div> <div class="event_item" data-id="4037">4037</div> </div>
Run a loop over your array to check if such an element exists.If it exists,add your class. 在数组上循环以检查是否存在此类元素。如果存在,请添加您的类。
orgsID.forEach(id => {
if($('.event_item[data-id='+id+']').length){
$('.event_item[data-id='+orgsID+']').addClass('show-item all');
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.