如何实现互不干扰的事件监听器,分别统计两个radio按钮组的分值?
分板块统计单选按钮得分解决方案
问题出在你使用了全局的document.querySelectorAll('input[type=radio]:checked'),这会获取页面上所有被选中的单选按钮,导致两个板块的得分被混在一起计算。
只需要将查询范围限制在各自的板块容器内即可解决:
修改后的「Report Admin」脚本
adminButtons.addEventListener('change', () => { adminResult.textContent = [...adminButtons.querySelectorAll('input[type=radio]:checked')] .reduce((acc, val) => acc + Number(val.value), 0) })
修改后的「Report Text」脚本
textButtons.addEventListener('change', () => { textResult.textContent = [...textButtons.querySelectorAll('input[type=radio]:checked')] .reduce((acc, val) => acc + Number(val.value), 0) })
原理说明
把原本全局的document.querySelectorAll替换为对应板块容器(adminButtons/textButtons)的querySelectorAll,这样每次计算时只会查找当前板块内部被选中的单选按钮,两个板块的得分统计就会独立进行,不会再出现互相干扰的情况。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

