[英]How do I hide all divs with a class name except those contained in an array of indices. With or without jquery
我有一個div列表:
<div class="person"></div>
<div class="person"></div>
<div class="person"></div>
我想隱藏除第107和第2之外的所有div。
我嘗試使用jquery filter
,但無法完全解決問題。
您可以過濾(從零開始)
var arr = [3, 107];
$('.person').filter(function(i) {
return $.inArray((i+1), arr) == -1;
}).hide();
收集人員列表,然后使用.eq()
進行選擇(基於0)。 這是一個簡單的示例:
var people = $('.person');
var exclude = people.eq(3).add(people.eq(5));
people.not(exclude).hide();
使用CSS選擇器或使用Jquery的選擇器,如下所示:
.person:nth-child(107) { display:none; }
$(".person").eq(106).hide();
您正在尋找“第n個孩子”選擇器。
以下將跳過兩個,並且每隔一個div將由其中的CSS規則選擇。
div.person:nth-child(1n+2)
在您的情況下:
div.person:nth-child(107), div.person:nth-child(2)
{
/* Rules here */
}
這是一個純粹的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';
})
您可以只使用普通的舊CSS:
.person {
display: none;
}
.person:nth-child(2),
.person:nth-child(107) {
display: block;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.