How super annoying is this? http://jsfiddle.net/b3xyx/
- I'm assigning a javascript function to each of my links using addEventListener.
- The loop iterates through each link, assigning an incremented variable x
- But actually when you click the links - instead of alerting the value of x, it alerts the final value of x; i.e. it has just assigned a pointer to x rather than copying it.
Check it out in action here: http://jsfiddle.net/b3xyx/ clicking any of the links will alert "4". Grr.
function goToSite(where){ alert("This would take you to " + where + ".com") } for(var x=1; x<=3; x++){ document.getElementById('link'+x).addEventListener('click', function(){goToSite(x)}) }
How can I work around this? Is there a way to create a true copy of a variable in this case?
EDIT: Thanks for suggesting the duplicate, but it doesn't seem to be a duplicate.
^ My updated code with:
function goToSite(whichOne){
return function(){
alert("This would take you to " + whichOne + ".com");
}
}
Still doesn't work.