0

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.

http://jsfiddle.net/aERRE/

^ My updated code with:

function goToSite(whichOne){
    return function(){
        alert("This would take you to " + whichOne + ".com");
    }
}

Still doesn't work.

Community
  • 1
  • 1
LittleBobbyTables
  • 4,361
  • 9
  • 38
  • 67

1 Answers1

0

in javascript, the for(var x...) transforms,the var x is moved to the begin of the function. and therefor the x in the goToSite refers to the global x you increased in each iteration, read about closures to understand why it happens...

Nadav Ben-Gal
  • 549
  • 3
  • 13
  • Thanks. Yeah I sort of understand that its actually pointing to the same variable each time, which will be the last value of the for loop. But I'm searching for a simple solution to this that I can use in the future. – LittleBobbyTables Feb 10 '13 at 22:45
  • how about defining an 'onclick' function for all your links , and let it just alert the id of 'this' (the link that was clicked on?) – Joel Blum Feb 10 '13 at 22:47
  • I would love to do this but have no idea how – LittleBobbyTables Feb 10 '13 at 22:55