我有动态生成的div部分。
<div class="webform submission-1">
<span class="first">1</span>
<span class="second">11</span>
</div>
<div class="webform submission-2">
<span class="first">2</span>
<span class="second">22</span>
</div>
<div class="webform submission-3">
<span class="first">3</span>
<span class="second">33</span>
</div>
<div class="webform submission-4">
<span class="first">4</span>
<span class="second">44</span>
</div>
...
<div class="webform submission-12">
<span class="first">12</span>
<span class="second">1212</span>
</div>
我想在submision-1和submittion-3之间显示span class =“ second”并隐藏class =“ first”,并在submision-4和submision-4之间显示span class =“ first”并隐藏class =“ second” -12 使用jquery如何使用动态类名检查类名是否存在并添加显示属性。
if($('.submission-2').length>0){ //need to check the between submission-1 to submission-3
$('.second').css('display','block');
$('.first').css('display','none');
}
else if($('.submission-4').length>0){ //need to check the between submission-4 to submission-12
$('.second').css('display','none');
$('.first').css('display','block');
}
答案 0 :(得分:3)
请勿为此使用JS。通过使用:nth-child
选择器,CSS能够更有效地实现这一目标。
.webform:nth-child(-n+3) .first {
display: none;
}
.webform:nth-child(n+4) .second {
display: none;
}
<div class="webform submission-1">
<span class="first">1</span>
<span class="second">11</span>
</div>
<div class="webform submission-2">
<span class="first">2</span>
<span class="second">22</span>
</div>
<div class="webform submission-3">
<span class="first">3</span>
<span class="second">33</span>
</div>
<div class="webform submission-4">
<span class="first">4</span>
<span class="second">44</span>
</div>
<div class="webform submission-12">
<span class="first">12</span>
<span class="second">1212</span>
</div>
这里有关于:nth-child selector
的更多阅读内容。