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

jQuery实现选中5个div后未选中项文字变蓝的问题修复

问题根因

原有代码存在3个核心问题导致效果异常:

  • 违反HTML ID唯一性规则:同页面内多个元素使用了相同的id="notSelected",jQuery通过ID选择器$('#notSelected')匹配时只会返回DOM树中第一个匹配的元素,这就是仅第一个未选中div文字变蓝的直接原因
  • 状态标记方案不合理:使用ID属性标记选中/未选中状态,ID本身设计为全局唯一标识,不适合做批量状态区分,应该用可复用的class类名实现状态样式
  • 缺少重复点击拦截:当前逻辑下重复点击同一个已选中的div会重复往统计数组里塞内容,导致选中计数不准
正确实现代码

CSS部分

把原来ID选择器的选中样式改成类选择器,适配批量状态匹配:

body {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
}

.test {
  display: flex;
  width: 100px;
  height: 100px;
  border: 2px solid transparent;
  background-color: #000000;
  margin-left: 2%;
  cursor: pointer;
}

/* 原ID选择器改为类选择器,适配批量状态匹配 */
.test.selected {
  border: 2px solid red;
}

.test:hover {
  border: 2px solid green;
}

.test p {
  color: #ffffff;
  margin: auto;
}

JS部分

替换原有ID操作为class操作,增加重复点击校验,选中数达5个时批量匹配所有未选中元素修改样式:

let testArray = []

$('.test').on('click', function() {
  const $current = $(this)
  // 已选中元素点击后直接跳过,避免重复计数
  if ($current.hasClass('selected')) return

  if (testArray.length < 5) {
    testArray.push($current.find('p').html())
    $current.addClass('selected')
    // 累计选中第5个时,批量修改所有未选中元素文字颜色
    if (testArray.length === 5) {
      $('.test:not(.selected)').each(function() {
        $(this).find('p').css('color', 'blue')
      })
    }
  }
})

HTML部分

删除所有重复的id="notSelected"属性,默认状态即为未选中,不需要额外加未选中标记:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="test">
  <p>test1</p>
</div>
<div class="test">
  <p>test2</p>
</div>
<div class="test">
  <p>test3</p>
</div>
<div class="test">
  <p>test4</p>
</div>
<div class="test">
  <p>test5</p>
</div>
<div class="test">
  <p>test6</p>
</div>
<div class="test">
  <p>test7</p>
</div>
<div class="test">
  <p>test8</p>
</div>
效果说明
  • 点击任意未选中div时,会给当前div加上selected类,显示红色边框
  • 同一div重复点击不会重复计数
  • 累计选中满5个div时,自动通过.test:not(.selected)选择器匹配所有未被选中的div,将内部文字统一设置为蓝色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 06:18:09