简体   繁体   English

Javascript - removeEventListener 不工作

[英]Javascript - removeEventListener not working

I am trying to add or remove EventListener using the following code.我正在尝试使用以下代码添加或删除 EventListener。

function a(input) {
    var b = document.getElementsByClassName("class_name");
  
    if (input == "add"){
      for (let i = 0; i < 5; i++){
        b[i].addEventListener("click", c); // This is working!
      }
    }
  
    if (input == "remove"){
      for (let i = 0; i < 5; i++){
        b[i].removeEventListener("click", c); // This is not working!
      }
    }
  
    function c(d){
      random_function(e); // "e" is a global variable
      e = d.currentTarget.getAttribute("id");
      random_function(e); // Running again the same function
    }
  }

addEventListener works as expected, but removeEventListener is not working. addEventListener 按预期工作,但 removeEventListener 不工作。 Why is that?这是为什么?

Every time a(input) is called, the interpreter creates a new c(d) function that has a reference different from the c(d) that was made a listener.每次调用a(input)时,解释器都会创建一个新的c(d) function,其引用不同于作为侦听器的c(d) Moving c(d) out of a(input) will solve the problem.c(d)a(input)中移出将解决问题。 (as long as function a can access function c) (只要functiona可以访问functionc)

function c(d){
  random_function(e);
  f = d.currentTarget.getAttribute("id");
  random_function(e); // Running again the same function.
}

function a(input) {
    var b = document.getElementsByClassName("class_name");
  
    if (input == "add"){
      for (let i = 0; i < 5; i++){
        b[i].addEventListener("click", c);
      }
    }
  
    if (input == "remove"){
      for (let i = 0; i < 5; i++){
        b[i].removeEventListener("click", c);
      }
    }
  }

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

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