茅侃侃
您也可以这样做:const ownAddEventListener = (scope, type, handler, capture) => { scope.addEventListener(type, handler, capture); return () => { scope.removeEventListener(type, handler, capture); }}然后,您可以像这样删除事件监听器:// Add event listenerconst disposer = ownAddEventListener(document.body, 'scroll', () => { // do something}, false);// Remove event listenerdisposer();
HUH函数
你不能 您必须使用命名函数或以某种方式存储引用。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);最好是以结构化的方式执行此操作,以便您可以标识不同的处理程序并将其删除。在上面的示例中,您显然只能删除最后一个处理程序。更新:您可以创建自己的处理程序处理程序(:)):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);