如何使用带有参数的函数添加和删除事件侦听器

如何使用带有参数的函数添加和删除事件侦听器

本文介绍了如何使用带有参数的函数添加和删除事件侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是一个常见问题,但我找不到通过搜索找到的相关答案。

Sorry if this is a common question, but I couldn't find any answers that seemed pertinent through searching.

如果我附加了这样的事件侦听器,则: / p>

If I attach an event listener like this:

window.addEventListener('scroll', function() { check_pos(box); }, false);

稍后尝试删除它似乎不起作用,像这样:

it doesn't seem to work to try to remove it later, like this:

window.removeEventListener('scroll', function() { check_pos(box); }, false);

我认为这是因为 addEventListener removeEventListener 方法想要引用相同的函数,而我为它们提供了匿名函数,尽管它们在代码上相同,但实际上并不相同。

I assume this is because the addEventListener and removeEventListener methods want a reference to the same function, while I've provided them with anonymous functions, which, while identical in code, are not literally the same.

如何更改代码以使对 removeEventListener 的调用正常工作? box参数是指我在屏幕上跟踪的< iframe> 的名称;也就是说,我希望能够为每个拥有的< iframe> 预订一次 scroll 事件(数量会有所不同),一旦 check_pos()函数测量到某个位置后,它将调用另一个函数,并删除事件侦听器以释放系统资源。

How can I change my code to get the call to removeEventListener to work? The "box" argument refers to the name of an <iframe> that I'm tracking on the screen; that is, I want to be able to subscribe to the scroll event once for each <iframe> that I have (the quantity varies), and once the check_pos() function measures a certain position, it will call another function and also remove the event listener to free up system resources.

我的直觉是该解决方案将涉及到闭包和/或命名匿名函数,但我不确定到底是什么样,并希望举一个具体的例子。

My hunch is that the solution will involve a closure and/or naming the anonymous function, but I'm not sure exactly what that looks like, and would appreciate a concrete example.

希望如此。

推荐答案

您是否尝试过维护对匿名函数的引用(如您建议的那样)?

Have you tried maintaining a reference to the anonymous function (like you suggested)?

所以:

var listener = function() {
  check_pos(box);
};

window.addEventListener('scroll', listener, false);
...
window.removeEventListener('scroll', listener, false);

Mozilla的文档同一件事。

Mozilla's docs suggest the same thing.

这篇关于如何使用带有参数的函数添加和删除事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:34