1

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?

James
  • 5,137
  • 5
  • 40
  • 80
Hugo P.
  • 35
  • 1
  • 8
  • 1
    Try using `myButtonList[i].className` or `myButtonList[i].classList.contains("flagged")` – Benjamin Gruenbaum Feb 13 '15 at 08:45
  • 2
    Another error you have here is http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Benjamin Gruenbaum Feb 13 '15 at 08:45
  • [1](http://stackoverflow.com/questions/6968147/passing-parameters-on-event-listeners-with-loops), [2](http://stackoverflow.com/questions/8909652/adding-click-event-listeners-in-loop) and others – Kirill Pisarev Feb 13 '15 at 08:46
  • Thanks a lot guys, I saw a few on the same topic but couldn't quite relate to my examples. Yours really helped, cheers ! – Hugo P. Feb 13 '15 at 14:15

2 Answers2

1
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);
}
alexP
  • 3,672
  • 7
  • 27
  • 36
0

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.

Justin
  • 56
  • 6