简体   繁体   English

点击循环事件监听器

[英]Event listener on click on loop

I'm trying to detect a click event on an dom element inside an array. 我正在尝试检测数组内dom元素上的click事件。

What I did so far, but it runs the loop before I even click. 到目前为止,我所做的只是在我什至没有单击之前就运行了循环。

for (var i = 0, len = block.length; i < len; i += 1) {
  block[i].addEventListener("click", blockIt());
}

What am I doing wrong? 我究竟做错了什么?

I just want to detect the click on the element I click that is in the array, so later I can look at the value and pass different functions depending of the value.. 我只想检测对数组中单击的元素的单击,因此以后我可以查看该值并根据该值传递不同的函数。

You're immediately calling the function. 您将立即调用该函数。 Change that to 更改为

for (var i = 0, len = block.length; i < len; i += 1) {
  block[i].addEventListener("click", blockIt); // no parenthesis here
}

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

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