原生JS如何解决点击事件向数组重复添加选中项问题
问题核心根因
你遇到的数组重复累积和事件冒泡完全无关,所有异常都来自两处逻辑bug:
- 第一,
addItems()函数的实现逻辑完全错位:它并非在点击时只把当前操作的项同步进数组,而是每次触发点击后,全量遍历页面上所有带item-selected类的元素,把每一个已选中项无差别重新push进数组一次。你可以对照控制台输出逐一验证:- 第一次点击item2时,页面上只有1个选中项,push1次,数组长度为1
- 第二次点击item3时,页面上共有2个选中项,把这2个全部重新push,数组长度就变成1+2=3
- 第三次点击item4时,页面上共有3个选中项,全部重新push,数组长度变成3+3=6
- 第四次点击item1时,页面上共有4个选中项,全部重新push,数组长度变成6+4=10
这个数值变化和你观察到的最终数组长度完全吻合,不存在事件冒泡导致的重复触发问题。
- 第二,原有逻辑里点击已选中项仅移除样式类,完全没有同步操作
itemsSelected数组,就算改了全量push的问题,取消选中时数组数据也不会和界面状态保持一致。
修复方案
直接删除原来全量遍历的addItems()函数,把选中/取消选中的逻辑和数组操作绑定在单次点击的事件流里:
- 点击触发时,先通过
event.target.closest('.item')定位到当前点击的item容器,避免因为点击到内部子元素(比如.item-title)导致选择器匹配失败 - 取到当前item对应的标题文本,判断当前是否为选中状态:
- 如果是已选中状态:移除
item-selected样式类,同时从itemsSelected数组里删除对应项 - 如果是未选中状态:加上
item-selected样式类,同时把项的文本push进itemsSelected数组
- 如果是已选中状态:移除
- 提交按钮触发时,直接读取
itemsSelected.length生成提示文案即可,不需要额外遍历页面元素
修正后的核心逻辑代码:
const noticeMod = document.getElementById('notice'); const noticeInner = document.getElementById('message'); const windowOverlay = document.getElementById('overlay'); let itemsSelected = []; // 弹窗相关函数实现保持不变 function appendMessage() { let elSpan = document.createElement('span'); elSpan.textContent = `You Downloaded ${itemsSelected.length} items.`; noticeInner.appendChild(elSpan); } function removeMessage() { let emptySpan = document.querySelectorAll('#message span'); if (emptySpan[0]) emptySpan[0].remove(); } function openNotification() { noticeMod.classList.add('show-notice'); windowOverlay.classList.add('show-overlay'); } function closeNotification() { noticeMod.classList.remove('show-notice'); windowOverlay.classList.remove('show-overlay'); } document.addEventListener('click', function(event) { if (event.target.matches('#submitBtn')) { appendMessage(); openNotification(); } if (event.target.matches('#closeBtn') || event.target.matches('#overlay')) { removeMessage(); closeNotification(); } // 修正后的item选中/取消选中逻辑 const clickedItem = event.target.closest('.item'); if (!clickedItem) return; const itemTitle = clickedItem.querySelector('.item-title').textContent; if (clickedItem.classList.contains('item-selected')) { clickedItem.classList.remove('item-selected'); const targetIndex = itemsSelected.indexOf(itemTitle); if (targetIndex > -1) itemsSelected.splice(targetIndex, 1); } else { clickedItem.classList.add('item-selected'); itemsSelected.push(itemTitle); } }, false);
补充注意点
- 原有循环里的
i变量没有用let/const声明,会被挂载为全局window属性,是潜在的内存泄漏问题,修复后的逻辑直接移除了这个无意义的全量遍历循环,从根源上避免了这类问题 - 用
closest()定位元素可以兼容点击到item内部任意子元素的场景,不需要额外判断子元素的选择器匹配
内容的提问来源于stack exchange,提问作者writhisdown
相关产品推荐
相关产品推荐

