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
相关产品推荐
相关产品推荐

