繁体   English   中英

在作为onclick函数的函数中删除事件侦听器/ onclick

[英]Removing event listener / onclick in the function that is the onclick function

我试图在与onclick调用的函数相同的函数中删除事件侦听器。

以下示例说明了我的问题。 我尝试使用这种构造的原因是将函数传递给视图对象,以便可以将其作为onclick函数添加到创建的元素中。

"use strict";

// Do I need var fun = function()... here or I could use only function fun() { ....}?
var fun = function(obj, num) {
  alert(obj.id + ' ' + num);
  obj.onclick = ""; // Version 1. This seems to work
  //obj.removeEventListener('click', ); // Version 2. What should I add after the comma to remove EventListener?

}

setFn(fun);

function setFn(fn) {

  var funct = fn;

  var val = 10;
  var elem = document.getElementById('test');
  // The next function works with and without return. What are the differences? Are there any possible memory leaks?
  elem.onclick = function() { funct(this, 11); }; // Version 1. Why in this case 'this' is not referring to the global 'window'?
  //elem.addEventListener('click', function() {funct(this, val); }); // Version 2.
}

先感谢您。

你不能那样做。 您没有引用在版本2中传递给.addEventListener()的匿名函数,因此无法将其删除。

一种可能是命名当前匿名函数,并将其作为第三个参数传递给funct

elem.addEventListener('click', function f() {funct(this, val, f); });

然后fun可以用它来删除侦听。

var fun = function(obj, num, bound_fn) {
  alert(obj.id + ' ' + num);
  if (bound_fn) {
    obj.removeEventListener('click', bound_fn);
  }
}

要删除事件监听器,您需要传递与添加的功能完全相同的功能。

"use strict";

var fun = function(obj, num, originalEventHandler) {
  alert(obj.id + ' ' + num);
  obj.removeEventListener('click', originalEventHandler);
}

function setFn(fn) {
  var element = document.getElementById('test');

  element.addEventListener('click', function eventHandler() {
    fn(this, 11, eventHandler);
  });
}

setFn(fun);

这应该工作。

暂无
暂无

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

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