I know当我知道类名时,如何隐藏除类的第一个实例之外的所有实例,但是当类是动态的时,如何完成此操作。 例如:
<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中的第1个应该是可见的,无论该类成为什么或有多少项存在。
答案 0 :(得分:0)
使用Javascript
您可以迭代它们并将该类与前一个类进行比较。 只有在类完全匹配时才会起作用,所以如果你有一个额外的类div,那将被视为&#34;不同&#34;。
$(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;
});
});
&#13;
<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>
&#13;
纯CSS
如果您知道可能出现的类,可以使用CSS仅显示第一个类。与pointed out in this answer一样,没有这样的选择器和#34;第一类&#34;。但是,提供了一个很好的解决方法,我们可以针对这种情况进行更改
.staticcontainername>.variable~.variable,
.staticcontainername>.variable2~.variable2,
.staticcontainername>.variable3~.variable3 {
display: none;
}
&#13;
<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>
&#13;