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>​

1

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.