How do I add and remove an event listener using a function with parameters?(如何使用带参数的函数添加和删除事件侦听器?)
问题描述
很抱歉,如果这是一个常见问题,但我无法通过搜索找到任何似乎相关的答案.
Sorry if this is a common question, but I couldn't find any answers that seemed pertinent through searching.
如果我像这样附加一个事件监听器:
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>
的名称;也就是说,我希望能够为我拥有的每个 订阅一次
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.
这篇关于如何使用带参数的函数添加和删除事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用带参数的函数添加和删除事件侦听器?
基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01