2017-06-14 57 views
0

know如何在知道类名时隐藏除类的第一个实例以外的所有类,但是如何在类为动态时完成此类动作。 例如:使用jQuery隐藏所有动态类的第一个实例

<div class="staticcontainername"> 
    <div class="variable"></div> <!-- This should show --> 
    <div class="variable"></div> 
    <div class="variable"></div> 
    <div class="variable2"></div> <!-- This should show --> 
    <div class="variable2"></div> 
    <div class="variable3"></div> <!-- This should show --> 
    <div class="variable3"></div> 
    <div class="variable3"></div> 
</div> 

只有每3周的div的第一次应该是可见的,不管是什么类成为或有多少项目的存在。

+0

所以,现在你的编辑之后,你只想要显示的容器中的每个新类的第一个实例 - 是正确的? –

+0

是的,只显示每个类的第一个实例,不管类名或数量如何 – Sam

回答

0

使用JavaScript

您可以在它们之间迭代,并与前一个比较级。 只有当类完全匹配时才会起作用,因此如果您有一个具有额外类的div,则会被视为“不同”。

$(function() { 
 
    var previousClass; 
 
    $('.staticcontainername div').each(function(index) { 
 
    // loop trough all elements in the container and get the class of the current element 
 
    var currentClass = $(this).attr('class'); 
 

 
    // compare the elements class with the previous one. 
 
    // if it matches, hide it 
 
    if (currentClass === previousClass) { 
 
     $(this).hide(); 
 
    } 
 

 
    // before we go to the next element, update the previousClass 
 
    // so we can compare it in the next iteration 
 
    previousClass = currentClass; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> 
 
<div class="staticcontainername"> 
 
    <div class="variable">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable">2</div> 
 
    <div class="variable">3</div> 
 
    <div class="variable2">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable2">2</div> 
 
    <div class="variable3">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable3">2</div> 
 
    <div class="variable3">3</div> 
 
</div>

纯CSS

如果你知道一个可能出现的可能的类,你可以使用CSS,只显示第一个。正如pointed out in this answer那样,没有像“第一堂课”那样的选择器。然而,提供了一个很好的解决方法,我们可以改变这种情况。

.staticcontainername>.variable~.variable, 
 
.staticcontainername>.variable2~.variable2, 
 
.staticcontainername>.variable3~.variable3 { 
 
    display: none; 
 
}
<div class="staticcontainername"> 
 
    <div class="variable">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable">2</div> 
 
    <div class="variable">3</div> 
 
    <div class="variable2">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable2">2</div> 
 
    <div class="variable3">1</div> 
 
    <!-- This should show --> 
 
    <div class="variable3">2</div> 
 
    <div class="variable3">3</div> 
 
</div>

+0

类名称只是替代任何结构后面的动态类的替代品,所以我不相信纯粹的CSS解决方案可行。 – Sam

+0

@Sam这就是为什么我开始使用智慧“如果你知道可能的类”,这可能是一个定义的集合。在这一点上我们不知道;) – JasperZelf

相关问题