[英]hide div if it doesn't have a certain class
I need to hide a class if it doesn't have the class active
. 如果没有active
类,我需要隐藏一个类。
$(document).ready(function() { if (!$('.active').hasClass('active')) { $(this).hide(); }; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="subheader active"> <p>Hello</p> </div> <div class="subheader"> <p>Goodbye</p> </div> <div class="subheader"> <p>Hello Again</p> </div>
To hide the subheader
that doesn't have the class active
, use 要隐藏没有active
类的subheader
,请使用
$('.subheader:not(.active)').hide();
A better solution would be, I think, to use pure CSS for this: 我认为,更好的解决方案是使用纯CSS:
.subheader {
display: none;
}
.subheader.active {
display: block;
}
As demonstrated in this snippet, that only uses jQuery to toggle the class, and uses CSS to decide what happens with it visually. 正如本片段所示,它只使用jQuery来切换类,并使用CSS来直观地决定它会发生什么。
$('.subheader').on('click', function(){ $('.subheader').toggleClass('active'); });
.subheader { display: none; } .subheader.active { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="subheader active"> <p>Hello, click to toggle</p> </div> <div class="subheader"> <p>Goodbye</p> </div> <div class="subheader"> <p>Hello Again</p> </div>
$(function() { $('.subheader:not(.active)').hide(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="subheader active"> <p>Hello</p> </div> <div class="subheader"> <p>Goodbye</p> </div> <div class="subheader"> <p>Hello Again</p> </div>
Or, with css: 或者,用css:
.subheader{ display: none; } .subheader.active{ display: block; }
<div class="subheader active"> <p>Hello</p> </div> <div class="subheader"> <p>Goodbye</p> </div> <div class="subheader"> <p>Hello Again</p> </div>
使用下面的代码来隐藏带有subheader类的div:
$('.subheader:not(.active)').hide();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.