[英]How do I hide all divs with a class name except those contained in an array of indices. With or without jquery
I have a list of divs: 我有一个div列表:
<div class="person"></div>
<div class="person"></div>
<div class="person"></div>
I want to hide all of the divs except the 107th and the 2nd. 我想隐藏除第107和第2之外的所有div。
I tried using jquery filter
, but couldn't quite wrap my head around a solution. 我尝试使用jquery filter
,但无法完全解决问题。
Gather a list of the people, and then use .eq()
to select them (it is 0 based). 收集人员列表,然后使用.eq()
进行选择(基于0)。 Here is a simple example: 这是一个简单的示例:
var people = $('.person');
var exclude = people.eq(3).add(people.eq(5));
people.not(exclude).hide();
Use CSS selector or use Jquery's selector like this: 使用CSS选择器或使用Jquery的选择器,如下所示:
.person:nth-child(107) { display:none; }
$(".person").eq(106).hide();
You're looking for the "nth-child" selector. 您正在寻找“第n个孩子”选择器。
The following will skip two and every other div will be selected by the CSS rules within. 以下将跳过两个,并且每隔一个div将由其中的CSS规则选择。
div.person:nth-child(1n+2)
In your case: 在您的情况下:
div.person:nth-child(107), div.person:nth-child(2)
{
/* Rules here */
}
Here is a pure JS solution, if that floats your boat, though straight-up CSS would also be an option: 这是一个纯粹的JS解决方案,如果可以解决的话,尽管也可以使用CSS直式:
[].forEach.call( document.querySelectorAll('div.person'), function(el) {
el.style.display = 'none';
});
[].forEach.call(document.querySelectorAll('div.person:nth-child(2), div.person:nth-child(107)', function(el) {
el.style.display = 'block';
})
You can just use plain old CSS: 您可以只使用普通的旧CSS:
.person {
display: none;
}
.person:nth-child(2),
.person:nth-child(107) {
display: block;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.