当所有Div都拥有Class" hideaddress"时,我有多个Div具有相同的Class。然后我插入一个新的Div。但当其中一个Divs没有Class" hideadress"我不想展示新的Div。但它不起作用。我怎么能改变这个?
if ($('div').hasClass('hideaddress')) {
$('<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address">new adress</div>').insertBefore('div.address:nth-child(1)');
}
&#13;
.hideaddress {
opacity: 0.3;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">1</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">2</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">3</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">4</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">5</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address showaddress">6</div>
&#13;
答案 0 :(得分:2)
而不是$('.hideaddress').length === $('.address').length
来检查公共类名是否完全等于div存在:
if ($('.hideaddress').length === $('.address').length) {
$('<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address">new adress</div>').insertBefore('div.address:nth-child(1)');
}
.hideaddress {
opacity: 0.3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">1</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">2</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">3</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">4</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">5</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address showaddress">6</div>
这也可以检查:
if ($('.showaddress').length) { // it will check if this div exists.