Anyone cares enough to explain this???
what do you mean by work? put it into a jsbin or how it's called
>>59468693
var has function scope. when the event handler triggers it will always refer to squares-length - 1.
"this" refers to the element that triggered the handler.
if you replace the "var" in your for loop with a "let", the code on the right will work too.
>>59468755
let me correct myself, "i" will be "squares.length" and hence the element you are retrieving from the array in the event handler will be undefined.
Thanks for the help. So event handler should only work on the last element?
>>59468890
no it wont work on any element because i will be out of bounds of the array.
you want to read about closures in javascript and about the difference between using "let" and "var" to declare variables.
replace "var" with "let" and your code will work.
give up anon
>>59469389
I will never give up!
>>59469164
Will do, thanks kind sir!
>>59469676
>thanks kind sir!
If I knew you spoke like such a faggot I wouldn't have bothered to help you.
>>59468755
If you want to take advantage of scoping you'd have to scope another variable in a smaller scope:for( var i=0; i< squares.length; ++i) {
{
let scoped_i = i;
squares[i].addEventListener("click", function() {
//squares[scoped_i]; will work here
});
}
}
you can just use let in the for loop.for(let i=0; i< squares.length; ++i) {
{
squares[i].addEventListener("click", function() {
//squares[i]; will work here
});
}
}