简体   繁体   English

为什么我不能使用 off() 删除事件侦听器?

[英]Why can't I remove event listeners using off()?

I am trying to remove dynamically an event from the DOM.我正在尝试从 DOM 中动态删除一个事件。 For this, I am using Chrome (version 79) dev tools, on page https://www.omgubuntu.co.uk/category/news?utm_source=menu为此,我使用 Chrome(版本 79)开发工具,页面https://www.omgubuntu.co.uk/category/news?utm_source=menu

In the Elements tab, I go to Event Listeners, and look for the 'load' event, and I find 3 events on the Window element.在 Elements 选项卡中,我转到 Event Listeners,并查找 'load' 事件,我在 Window 元素上找到了 3 个事件。 So in the console, I type:所以在控制台中,我输入:

$(window).off('load');

The command executes with no error, but nothing seemed to have changed, even when I press the refresh button in the events section.命令执行没有错误,但似乎没有任何改变,即使我按下事件部分中的刷新按钮。 I am expecting all the 'load' events for Window to disappear.我期待 Window 的所有“加载”事件都会消失。

在此处输入图片说明

I have this same problem on many other sites, but works fine on my local webpage (this is how I know I am using JQuery the right way)...我在许多其他网站上也有同样的问题,但在我的本地网页上运行良好(这就是我知道我以正确的方式使用 JQuery 的方式)...

.off() only removes events that were added via the .on() method, so any events added with other APIs wouldn't be affected. .off()仅删除通过.on()方法添加的事件,因此任何通过其他 API 添加的事件都不会受到影响。

Now, when you say even when I press the refresh button in the events section.现在,当您说即使我按下事件部分中的刷新按钮时。 I am expecting all the 'load' events for Window to disappear.我期待 Window 的所有“加载”事件都会消失。 , you misunderstand the nature of how a page is processed. ,您误解了页面处理方式的性质。 If you refresh the page, all of its code is processed again, therefore even if you were successful in removing the handlers in your console, they would all come back because the page is starting all over again.如果您刷新页面,它的所有代码都会再次处理,因此即使您成功删除了控制台中的处理程序,它们也会全部返回,因为页面会重新开始。

Understand that what you do in the console only affects the current instance of the page loaded within the browser.了解您在控制台中执行的操作只会影响浏览器中加载的页面的当前实例。

To remove an existing listener, use getEventListeners command line API:要删除现有侦听器,请使用getEventListeners命令行 API:

getEventListeners(window).load.forEach(x=>window.removeEventListener('load',x.listener))

or simply click the Remove button in Elements Event listeners panel:或者只需单击 Elements Event listeners面板中的Remove按钮:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM