简体   繁体   中英

Event listener on click on loop

I'm trying to detect a click event on an dom element inside an array.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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