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

点击按钮调用removeEventListener移除div点击事件失效问题求助

为什么你的removeEventListener无法正常工作?

Hey there! The issue here comes down to how removeEventListener actually works—let me break it down for you:

When you use addEventListener, you're telling the browser to associate a specific function reference with that event. To remove it later with removeEventListener, you need to pass that exact same function reference back to the browser.

In your code, you bound the func function directly to the click event:

document.getElementById('divv').addEventListener("click", func)

But when you tried to remove it, you passed a brand new anonymous function that wraps func:

document.getElementById('divv').removeEventListener("click",function(){func()});

These are two completely different function objects, so the browser can't find the original event handler to remove.

修复方案

Simply pass the original func reference to removeEventListener instead of wrapping it in an anonymous function. Here's the corrected code:

JavaScript

document.getElementById('divv').addEventListener("click", func);

function func(a) { 
  alert("oooo"); 
}

function abc() { 
  // Use the exact same func reference you used to bind the event
  document.getElementById('divv').removeEventListener("click", func); 
}

HTML

<div id="divv">This is vivek</div>
<button onclick="abc()">Remove</button>

额外注意事项

  • Never bind an anonymous function if you think you'll need to remove it later—you won't have a reference to pass to removeEventListener.
  • Make sure the event type (like "click") matches exactly between addEventListener and removeEventListener (it's case-sensitive!).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:47:30