Hugo P.
Hugo P.

Reputation: 35

Loop and Functions

I'm having troubles gathering information about clicked eventListeners.

I have this loop which builds an array:

myButtonList = document.getElementsByTagName('a');
myAnchorList = [];

for (i=0; i < myButtonList.length;i++) {
    if (myButtonList[i].getAttribute('class') == 'flagged') {
        myAnchorList.push(myButtonList[i]);
    }
}

For each <a> put into myAnchorList array, I also create another array storing other informations from the same tag (classe and other atrributes).

Here's where I'm struggling. I'm trying to set up an eventListener to send me back those information when those <a> are being clicked. But somehow, the fact that I create a function (for the eventListener) within a loop breaks everything.

for (i=0; i < myAnchorList.length; i++) {
    myAnchorList[i].addEventListener("click", function(i){
        console.log(alpha+' - '+beta[i]+" - "+charlie[i]);
    });
}

My values will either be undefined or some other values which will be the same for each buttons I clicked. alpha is working well as it doesn't depend on any iteration of the loop, but not the others.

Can anybody see what I'm doing wrong here?

Upvotes: 1

Views: 85

Answers (2)

alexP
alexP

Reputation: 3765

for (var i = 0; i < myAnchorList.length; i++) {
    (function (i) { //Passes i to your function
        myAnchorList[i].addEventListener("click", function () {
            console.log(alpha+' - '+beta[i]+" - "+charlie[i]);
        });
    })(i);
}

Upvotes: 1

Justin
Justin

Reputation: 56

The variable "i" in closure that you created in the loop will always retrieve the last value(myAnchorList.length - 1). You shouldn't create closure in a loop, and you can use a "factory" method to create closure instead.

Upvotes: 0

Related Questions