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

JQuery中div点击事件叠加触发,函数多次执行问题求助

解决点击事件重复绑定导致函数多次执行的问题

嘿,我完全懂你遇到的糟心事——每次点击那个切换按钮,addToShortList和removefromShortList函数就会被执行好几次,这都是因为你的代码在重复叠加绑定事件,没处理旧的事件处理程序导致的。

先给你揪出问题根源:你原来的写法里,每次调用addToShortList时,都会用.on('click', removefromShortList(element))给元素绑定新的点击事件,但这里还有个小错误——你不是传递函数引用,而是直接执行了removefromShortList(element),然后把执行结果当成事件处理程序了!而且就算你传对了函数,每次切换类都绑定新事件,旧的事件也没被移除,次数多了自然会堆起来,点击一次触发N次函数。

下面给你两种靠谱的解决办法,按需选就行:

方法一:用事件委托(推荐,更高效)

这种方式只需要绑定一次事件,不用每次切换状态都折腾绑定/解绑,靠事件冒泡来处理。

<div class="document-short-list-item" data-d-id="5" data-w-id="16" data-s-id="15">Klik her for at tilføje</div>
// 页面加载完成后,给父元素(比如document或者更接近的容器)绑定一次事件
$(function() {
  // 监听未添加状态的元素点击
  $(document).on('click', '.document-short-list-item', function() {
    addToShortList(this);
  });

  // 监听已添加状态的元素点击
  $(document).on('click', '.document-short-list-item-added', function() {
    removefromShortList(this);
  });
});

function addToShortList(element) {
  $(element).removeClass('document-short-list-item').addClass('document-short-list-item-added');
  // 这里不用再绑定click事件啦!
}

function removefromShortList(element) {
  $(element).removeClass('document-short-list-item-added').addClass('document-short-list-item');
  // 同样不用绑定事件
}

原理很简单:父元素会监听所有子元素的点击事件,当点击发生时,它会判断目标元素的类,然后执行对应的函数。不管元素怎么切换类,只需要绑定一次事件,完全不会有叠加的问题。

方法二:解绑旧事件后再绑定新事件

如果你不想用事件委托,也可以在每次绑定新事件前,先移除元素上已有的点击事件:

$(function() {
  $(".document-short-list-item").click(function () { 
    addToShortList(this); 
  });
});

function addToShortList(element) {
  $(element)
    .removeClass('document-short-list-item')
    .addClass('document-short-list-item-added')
    .off('click') // 先清空所有旧的click事件
    .on('click', function() { // 再绑定新的事件处理函数
      removefromShortList(this);
    });
}

function removefromShortList(element) {
  $(element)
    .removeClass('document-short-list-item-added')
    .addClass('document-short-list-item')
    .off('click') // 清空旧事件
    .on('click', function() { // 绑定新事件
      addToShortList(this);
    });
}

这里用.off('click')把元素上之前绑定的所有click事件都移除,再绑定新的,这样就不会有事件叠加的问题了。不过这种方式每次都要解绑再绑定,效率不如事件委托高,适合元素不多的场景。

内容的提问来源于stack exchange,提问作者KeldJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:27:49