简体   繁体   English

addEventListener的关闭位置在哪里?

[英]Where to put closure for addEventListener?

I read that one can use closures for addEventListener in loops ( addEventListener using for loop and passing values ). 我读到可以在循环中为addEventListener使用闭包( addEventListener使用for循环和传递值 )。

However, this method does not work with a more complex example: 但是,此方法不适用于更复杂的示例:

function f(fevent) {
  var a = document.createElement('a');
  a.innerHTML = 'Test';
  a.href = '#';
  a.addEventListener('click', fevent);
  return a;
};

for (l = 0; l < 2; l += 1) {
  for (h = 0; h < 2; h += 1) {
    document.body.appendChild(
    f(function() {alert(l+','+h);})
    );
  }
}

https://jsfiddle.net/yasnujzq/ https://jsfiddle.net/yasnujzq/

Edit: I want is that the click event on the anchors to alert different combinations (0,0), (1,0), (0,1), and (1,1). 编辑:我想要的是锚点上的click事件,以警告不同的组合(0,0),(1,0),(0,1)和(1,1)。 But it always alerts (2,2). 但它始终会发出警报(2,2)。

Here is what I tried with the closure method from above: 这是我从上面尝试的闭包方法:

function f(fevent) {
  var a = document.createElement('a');
  a.innerHTML = 'Test';
  a.href = '#';
  a.addEventListener('click', fevent);
  return a;
};

for (l = 0; l < 2; l += 1) {
  for (h = 0; h < 2; h += 1) {
    (function() {
                document.body.appendChild(
                f(function() {alert(l+','+h);})
                );
    }());
  }

https://jsfiddle.net/72sg8d5n/ https://jsfiddle.net/72sg8d5n/

I also tried to add arguments to the closure: 我还尝试向闭包添加参数:

function f(fevent) {
  var a = document.createElement('a');
  a.innerHTML = 'Test';
  a.href = '#';
  a.addEventListener('click', fevent);
  return a;
};

for (l = 0; l < 2; l += 1) {
  for (h = 0; h < 2; h += 1) {
    (function() {
                document.body.appendChild(
                f(function() {alert(l+','+h);})
                );
    }(l,h));
  }
}

https://jsfiddle.net/wxodr8p6/ https://jsfiddle.net/wxodr8p6/

Maybe someone can enlighten me on this. 也许有人可以启发我。

Edit : Here is a working fiddle with the method from the accepted solution below: 编辑 :这是从下面的可接受的解决方案方法工作的小提琴:

https://jsfiddle.net/87zp4dkr/ https://jsfiddle.net/87zp4dkr/

 (function() { document.body.appendChild( f(function() {alert(l+','+h);}) ); }(l,h)); 

On the last line of this code you are passing the function two arguments. 在此代码的最后一行,您将向函数传递两个参数。

On the first line, you are not accepting any arguments. 在第一行,您不接受任何参数。

You don't use the values you pass to that function, you are still using the ones from the loop (which change each time the loop goes around). 您无需使用传递给该函数的值,而仍使用循环中的值(每次循环时,这些值都会改变)。

(function(my_l, my_h) {
            document.body.appendChild(
            f(function() {alert(my_l+','+my_h);})
            );
}(l,h));

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

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