如果 div 有一个特定的子项,我正在尝试更改它的背景(和其他样式)。我正在使用 .length 来检查特定子项是否存在,但即使它不存在,div 也会从 jquery if 语句中获取样式。我的 HTML:
<div class="full-text-panel">
<div class="main-wrap">
<h1 class="home-h1">This is a header</h1>
<a class="body-button">This is a button</a>
</div><!--end main-wrap-->
</div><!--end full-text-panel-->
还有我的 jQuery:
var fullText = $('.full-text-panel');
var bodyButton = $('.body-button');
if ( $(".full-text-panel .body-button").length > 0 ) {
fullText.css("background", "red");
} else {
fullText.css("background", "blue");
}
我认为这行得通,但是两个全文本面板都采用了背景红色样式。我做错了什么?
最佳答案
$(function(){
$('.full-text-panel:has(.body-button)').addClass('red');
});
.full-text-panel{
background:blue;
}
.red{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="full-text-panel">
<div class="main-wrap">
<h1 class="home-h1">This is a header</h1>
<a class="body-button">This is a button</a>
</div><!--end main-wrap-->
</div><!--end full-text-panel-->
<div class="full-text-panel">
<div class="main-wrap">
<h1 class="home-h1">This is a header</h1>
</div><!--end main-wrap-->
</div><!--end full-text-panel-->
关于javascript - 如果 div 具有特定的 Child,则更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29349689/