gpt4 book ai didi

javascript - jQuery 选择具有空跨度的 div

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:59 25 4
gpt4 key购买 nike

我有一个内部有 2 个 span 的 div。我只想在两个跨度都为空时才将此 div 着色为红色。当最小一个跨度具有值时,我想为这个特定的父 div 着色,例如蓝色。这个怎么做?现在我为所有 div 着色,但我只想为具有空跨度的父级着色。我的代码如下

$('#t').on('click', function(){
var sum = 0;
$('div span').each(function(){
sum += parseFloat($(this).text().length);
if (sum != 0) {
$(this).closest('section').find('.div').css("background", "blue");
} else {
$(this).closest('section').find('.div').css("background", "red");
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div class="container">
<div class="row"></div>
<div class="row">
<div class="col-sm-3">
<div class="div">
<span></span>
<span></span>
</div>
</div>
<div class="col-sm-3">
<div class="div">
<span>b-1</span>
<span>b-2</span>
</div>
</div>
</div>
<div class="row"></div>
</div>
</section>

<section>
<div class="container">
<div class="row">
<div class="col-sm-12">
<input type="button" value="ss" id="t">
</div>
</div>
</div>
</section>

最佳答案

你可以使用过滤器

$('#t').on('click', function(e) {
// just removed your other code for now

e.preventDefault();

$('.div').css('background', 'blue') // start all divs as blue
.filter(function() {
return $(this).children('span:empty').length === 2; // filter any divs with 2 empty spans
}).css('background', 'red'); // make filtered results red
});
.div {
min-height: 100px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div class="container">
<div class="row"></div>
<div class="row">
<div class="col-sm-3">
<div class="div">
<span></span>
<span></span>
</div>
</div>
<div class="col-sm-3">
<div class="div">
<span>b-1</span>
<span>b-2</span>
</div>
</div>
</div>
<div class="row"></div>
</div>
</section>

<section>
<div class="container">
<div class="row">
<div class="col-sm-12">
<input type="button" value="ss" id="t">
</div>
</div>
</div>
</section>

关于javascript - jQuery 选择具有空跨度的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48097681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com