点击按钮调用removeEventListener移除div点击事件失效问题求助
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 betweenaddEventListenerandremoveEventListener(it's case-sensitive!).
内容的提问来源于stack exchange,提问作者Rajesh purohit

