It's a small piece of code, but I can't get it to work.
I have a menu which is filled dynamically with javascript, and I add an eventlistener on click for every button.
Now every button needs a different function, so I loop through them

```
var list = $("a");
for (var i=0; i<list.length; i++) {
    $(list[i]).on("click",function(){alert(i);});
}

```

With this code every button will give me an alert with 5, instead of 1,2,3,...
How do I fix this?
['https://Stackoverflow.com/questions/22361630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Use [each()](https://api.jquery.com/each/) that's what it's for:

```
var list = $("a");
list.each(function(index){
    $(this).on("click", function(){alert(index);});
});

```

[DEMO](http://jsfiddle.net/7HeeA/)
The value of i changes in the loop, but after the loop is finished the value of i is 5. Whenever you call the alert, it is looking for the variable i, whose value is now 5. You need to store the increment value of i somewhere for each thing. In this example, I give each button an HTML5 data attribute called `data-myvalue`.

```
for (var i=0;i<ins.length;i++){
    ins[i].setAttribute('data-myvalue',i);
    ins[i].addEventListener('click',
           function(){alert(this.getAttribute('data-myvalue'));});
}

```

[jsfiddle](http://jsfiddle.net/PgYaz/)

But you can also store the information in javascript array.