1

I am wondering why the statement "let im = _imgs[i];" is indispensable in this situation. Essentially, the _imgs are an array of image elements. But if I add the eventhandlers by _imgs[i].addEventListener("click", function(){clickImage(_imgs[i]);}, false);, it won't work.

Can anyone explain why? Thanks a lot!

function init()
{
    _imgs = document.querySelectorAll("#block2 img");
    console.log(_imgs.length);
    _clicked = new Object();
    for(var i = 0; i < _imgs.length; i++)    
    {      
        let im = _imgs[i];
        _imgs[i].addEventListener("click", function(){clickImage(im);}, false);
        _clicked[_imgs[i].id] = 0;
    }
    console.log("hi");
}
Christine
  • 93
  • 1
  • 5
  • Can you edit your post to include the `clickImage` function? Also, please elaborate on why your code is not having the expected result. – Brendan Bond Dec 13 '21 at 07:55
  • `let im = _imgs[i];` introduces a new variable within the loop so the `im` in `clickImage(im);` is an independent variable. With `clickImage(_imgs[i]);` the `i` is always the same variable (because it was defined with `var`), so at the time when the event listener is called `i` is equal to `_imgs.length` for each of them. `…is indispensable in this situation…` it isn't if you change `var i = 0` to `let i = 0`. – t.niese Dec 13 '21 at 08:01

0 Answers0