2

I have a list of 3 links, that I wanna iterate through, so each one of them can do something. But when I use the for-loop, it only gives me 3 in the console, which is the number of links in the list. I wanna the console to show each of them like so: 0, 1, 2;

Also how can I get the index position of each of the links?

See code here: http://jsfiddle.net/c8Wdj/

No jQuery or any library please...

JavaScript:

(function(){
    var triggers = document.getElementById('some-list').getElementsByTagName('a');

    for (var i = 0, max = triggers.length; i < max; i += 1) {
        triggers[i].addEventListener('mouseenter', function(e) {

            console.log(i);

        }, false);
    }

}());

HTML:

<ul id="some-list">
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
</ul>​

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Shaoz
  • 10,573
  • 26
  • 72
  • 100
  • Possible duplicate of http://stackoverflow.com/questions/1552941/variables-in-anonymous-functions-can-someone-explain-the-following – Salman A May 26 '12 at 16:55

2 Answers2

3

for has no scope, so when you console.log(i), it's using the latest value for i. Try this:

for (var i = 0, max = triggers.length; i < max; i += 1) {
    (function(num){
        triggers[i].addEventListener('mouseenter', function(e) {
            console.log(num);
        }, false);
    })(i);
}
jcampbelly
  • 652
  • 1
  • 7
  • 11
0

A common approach is to create a new variable scope in each iteration of the loop by invoking a function, passing i into it, and returning a function that references that value.

But if you're just needing to reference some lightweight data like a number, another approach is simply to put an expando property on the element.

for (var i = 0, max = triggers.length; i < max; i += 1) {
    triggers[i].__i__ = i;
    triggers[i].addEventListener('mouseenter', function(e) {
        console.log(this.__i__);
    }, false);
}

This doesn't require the overhead of the nested variable scope.

DEMO: http://jsfiddle.net/c8Wdj/5/

May be issues with IE6 (I don't remember), but that shouldn't matter since you're hopefully not supporting its JS environment anymore. :)