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

jQuery点击已选中div取消选中并移除数组值失效如何解决

问题根因

你的.selected点击事件不生效是核心问题+小bug共同导致的:

  • 事件绑定时机错误:页面初始加载时所有div都只有none类,不存在带selected类的元素。直接调用$('.selected').on('click')只会给页面初始加载时就匹配选择器的元素绑定事件,后续动态添加selected类的div不会被绑定事件,自然点击无响应。
  • filter回调内this指向错误:普通函数作为Array.filter的回调时,内部this不指向当前点击的DOM元素,会导致获取p标签文本的逻辑失效,无法正确过滤数组内容。
  • 额外样式bug:CSS中none:hover的光标属性拼写错误,poiner应为pointer。
修复实现

最优方案是使用事件委托,将点击事件统一绑定在初始就存在的.test元素上,在事件内部通过判断当前元素的类名走对应选中/取消选中逻辑,避免动态类绑定失效问题,修复后完整代码如下:

修复后JS代码

let testArray = []

// 统一给所有初始存在的.test元素绑定点击事件,兼容动态类状态变化
$('.test').on('click', function() {
  const $current = $(this)
  const currentText = $current.find('p').html()

  // 不可选状态直接拦截点击
  if ($current.hasClass('notSelected')) return

  // 已选中状态:走取消选中逻辑
  if ($current.hasClass('selected')) {
    testArray = testArray.filter(item => item !== currentText)
    $current.removeClass('selected').addClass('none')
    // 取消选中后移除所有不可选状态,恢复未选中项的可选状态
    $('.test:not(.selected)').removeClass('notSelected').addClass('none')
    console.log(testArray)
    return
  }

  // 未选中状态:走选中逻辑
  if ($current.hasClass('none')) {
    testArray.push(currentText)
    $current.removeClass('none').addClass('selected')
    // 选中数达到5个时,其余项设为不可选
    if (testArray.length === 5) {
      $('.test:not(.selected)').removeClass('none').addClass('notSelected')
    }
    console.log(testArray)
  }
})

修复后CSS代码

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%;
}

.selected {
  border: 2px solid green;
  cursor: pointer;
}

.notSelected {
  border: 2px solid red;
  cursor: default;
}

.none:hover {
  /* 修复拼写错误 */
  cursor: pointer;
}

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

HTML代码(无需修改)

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

<div class="test none">
  <p>test1</p>
</div>
<div class="test none">
  <p>test2</p>
</div>
<div class="test none">
  <p>test3</p>
</div>
<div class="test none">
  <p>test4</p>
</div>
<div class="test none">
  <p>test5</p>
</div>
<div class="test none">
  <p>test6</p>
</div>
<div class="test none">
  <p>test7</p>
</div>
<div class="test none">
  <p>test8</p>
</div>
逻辑说明
  • 所有点击事件统一绑定在初始就存在的.test元素上,不管后续类名怎么动态变化,事件都能正常触发
  • 提前缓存当前点击元素和对应p标签文本,避免回调函数内this指向混乱的问题
  • 选中数量达到5个时自动给剩余未选项加notSelected类拦截点击,任意取消一个选中项后自动恢复剩余项的可选状态
  • 修复了CSS光标拼写错误,hover时手型效果正常显示

内容的提问来源于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:30:53