Defining anonymous functions in a loop including the looping variable?

rodericksnail

New Member
I know that this code doesn't work and I also know why.However, I do not know how to fix it:JavaScript:\[code\] document.addEventListener('DOMContentLoaded', function() { for(var i = 1; i <= 3; i++) { $('a' + i).addEventListener('click', function() { console.log(i); }); } }\[/code\]HTML:\[code\]<a href="http://stackoverflow.com/questions/8334756/#" id="a1">1</a><a href="http://stackoverflow.com/questions/8334756/#" id="a2">2</a><a href="http://stackoverflow.com/questions/8334756/#" id="a3">3</a>\[/code\]I want it to print the number of the link you clicked, not just "4".I will prefer to avoid using the attributes of the node (id or content), but rather fix the loop.
 
Top