I'm not sure how you are trying to do this (it would be better to show the loop code), but overall it is not very safe for creating functions in a loop, because you can mistakenly refer to a variable changing inside the loop, so finally you get all functions using the same identifier. The solution for this is to use some helper function:
var bindClick = function (element, id, username) { element.addEventListener('click', function () { downVote(id, username); }, false); }, i, mybutton; for (i = 0 ; i < amountOfUsers ; ++i) { mybutton = document.getElementById('downvote-handle-' + i); bindClick(mybutton, i, usernames[i]); }
thus i value is copied (passed by value) and is safe.
this can be done with an anonymous function, the result will be the same (but IMHO less readable):
for (i = 0 ; i < amountOfUsers ; ++i) { mybutton = document.getElementById('downvote-handle-' + i); (function (element, id, username) { element.addEventListener('click', function () { downVote(id, username); }, false); }(mybutton, i, userames[i])); }
source share