You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery实现含双span的div按span内容状态设置背景色

解决思路与修正代码

你的核心问题在于当前代码是遍历所有span后,统一给整个section内的所有.div设置样式,没有针对单个父div单独判断它下面两个span的状态。我们需要调整逻辑,逐个检查每个.div下的span内容,再单独设置它的背景色。

修正后的完整代码

<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>

<script>
$('#t').on('click', function(){
  // 遍历每个需要判断的父div
  $('.div').each(function(){
    let totalLength = 0;
    // 只计算当前div下的两个span的文本长度
    $(this).find('span').each(function(){
      totalLength += $(this).text().trim().length; // 加trim避免空格误判
    });
    // 根据总长度判断设置背景色
    if(totalLength === 0){
      $(this).css('background', 'red');
    } else {
      $(this).css('background', 'blue');
    }
  });
});
</script>

关键修改说明

  • 遍历对象从span改为.div:这样我们能单独处理每个父容器,不会出现“一竿子打翻一船人”的情况
  • 限定span的范围:用$(this).find('span')只获取当前div下的span,避免跨容器计算
  • 增加trim()处理:防止span里有空格时被误判为有内容,更符合“为空”的实际需求
  • 单独设置当前div的样式:直接给$(this)(当前遍历的.div)设置背景色,精准定位目标元素

内容的提问来源于stack exchange,提问作者MMPL1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:06:04