How to removeEventListener that is addEventListener with anonymous function?(如何删除带有匿名函数的 addEventListener 的EventListener?)
问题描述
function doSomethingWith(param)
{
document.body.addEventListener(
'scroll',
function()
{
document.write(param);
},
false
); // An event that I want to remove later
}
setTimeout(
function()
{
document.body.removeEventListener('scroll', HANDLER ,false);
// What HANDLER should I specify to remove the anonymous handler above?
},
3000
);
doSomethingWith('Test. ');
推荐答案
你不能.您必须使用命名函数或以某种方式存储引用.
You can't. You have to use a named function or store the reference somehow.
var handler;
function doSomethingWith(param) {
handler = function(){
document.write(param);
};
document.body.addEventListener('scroll', handler,false);
}
setTimeout(function() {
document.body.removeEventListener('scroll', handler ,false);
}, 3000);
最好以结构化的方式执行此操作,以便您可以识别不同的处理程序并将其删除.在上面的示例中,您显然只能删除最后一个处理程序.
The best would be to do this in a structured way, so that you can identify different handlers and remove them. In the example above, you obviously could only remove the last handler.
更新:
您可以创建自己的处理程序处理程序 (:)):
You could create your own handler handler (:)) :
var Handler = (function(){
var i = 1,
listeners = {};
return {
addListener: function(element, event, handler, capture) {
element.addEventListener(event, handler, capture);
listeners[i] = {element: element,
event: event,
handler: handler,
capture: capture};
return i++;
},
removeListener: function(id) {
if(id in listeners) {
var h = listeners[id];
h.element.removeEventListener(h.event, h.handler, h.capture);
delete listeners[id];
}
}
};
}());
然后你可以使用它:
function doSomethingWith(param) {
return Handler.addListener(document.body, 'scroll', function() {
document.write(param);
}, false);
}
var handler = doSomethingWith('Test. ');
setTimeout(function() {
Handler.removeListener(handler);
}, 3000);
演示
这篇关于如何删除带有匿名函数的 addEventListener 的EventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何删除带有匿名函数的 addEventListener 的EventListener?


- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01