
addeventlistener事件失效之惑
在使用addeventlistener事件绑定时,为什么点击事件函数只能执行一次?
代码示例
const dataarr = [
{ id: 1, icon: '火龙果.png', ischecked: true, num: 2, price: 6 },
{ id: 2, icon: '荔枝.png', ischecked: false, num: 7, price: 20 },
// ...省略部分数据
];
// 个数添加功能
const jia = document.queryselectorall('.increase');
const jian = document.queryselectorall('.decrease');
for (let i = 0; i < jia.length; i++) {
jia[i].addeventlistener('click', function () {
console.log(123);
dataarr[i].num++;
render(dataarr);
});
}运行代码后,当第一次点击按钮时,事件函数正常执行,但再次点击按钮时却没有响应。
原因分析
如查到的答案所言,innerhtml会替换元素内容,导致事件绑定销毁。在本例中,渲染函数render会使用innerhtml更新元素内容,因此每次渲染都会销毁之前的事件绑定。
解决方案
推荐使用事件委托方式解决此问题。在父节点上绑定点击事件,并在回调函数中通过event.target判断点击了哪个按钮。
document.querySelector('.parent').addEventListener('click', function(event) {
const target = event.target;
if (target.closest('.increase')) {
// 按钮增加逻辑
} else if (target.closest('.decrease')) {
// 按钮减少逻辑
}
});通过事件委托,无论元素内容如何变化,事件绑定始终存在于父节点上,因此可以正常触发事件函数。
以上就是使用addEventListener事件绑定时,为什么点击事件函数只能执行一次?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号