javascript - why undefined in the function of addEventListener? -
this question has answer here:
i'm trying add mouseenter
event listener elements change childnodes' opacity. use for
add listener, , can output childnodes properly, in function it's "undefined". have no idea why.
html:
<article class="index-image-article rel"> <section class="index-image-info"> // elements </section> <div class="index-image-excerpt mask table"> // elements </div> </article>
javascript:
var indeximagearticle = document.queryselectorall(".index-image-article"); var indeximageinfo = document.queryselectorall(".index-image-info"); var indeximageexcerpt = document.queryselectorall(".index-image-excerpt"); for(var = 0; < indeximagearticle.length; i++) { console.log(indeximageinfo[i]); // output indeximagearticle[i].addeventlistener("mouseenter", function() { indeximageinfo[i].style.opacity = 1; indeximageexcerpt[i].style.opacity = 0; }); }
the output of console.log
is:
<section class="index-image-info">…</section> <section class="index-image-info">…</section> <section class="index-image-info">…</section> <section class="index-image-info">…</section>
and error:
uncaught typeerror: cannot read property 'style' of undefined(anonymous function)
the undefined
point indeximageinfo[i]
this 1 of strange nuances of variable scoping rules in javascript.
really boils down 1 thing, @ point of adding event handler, i
has right value. @ point of executing event handler i
has been incremented indeximagearticle.length
, , therefore outside of bounds of array.
it can fixed using block maintains scope of variable, iife 1 way:
for(var = 0; < indeximagearticle.length; i++) { console.log(indeximageinfo[i]); // output (function(x){ indeximagearticle[x].addeventlistener("mouseenter", function() { indeximageinfo[x].style.opacity = 1; indeximageexcerpt[x].style.opacity = 0; }); })(i) }
Comments
Post a Comment