1

I'm trying to give a list of generated link tags a function, this is the way i'm doing this.

for (i = 0; i < friendsXML.length; i++) {
                friendListInDiv = document.createElement("p");
                var link = document.createElement("a");
                link.onclick = function() {
                    openChat(friendsXML[i].textContent)
                };
                var friendText = document
                        .createTextNode(friendsXML[i].textContent + ":"
                                + statusXML[i].textContent);
                link.appendChild(friendText);
                friendListInDiv.appendChild(link);
                friendDiv.appendChild(friendListInDiv);
            }

Currently the openChat(name) function only calls an alert to test its value

function openChat(name){
alert(name);
}

Now the problem is that when I go to my webpage and click one of the generated links it always alerts the first name (every link alerts the same name, the first one). So my question is how can I fix it that I alert the correct name for each link?

Here is a pastebin of the full code if necessary http://pastebin.com/8ggE7SHs

  • 1
    Take a look at the explanation of the problem: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – dfsq Mar 29 '15 at 18:15

1 Answers1

1

wrap it in a function closure:

for (i = 0; i < friendsXML.length; i++) {
(function(i) {
                friendListInDiv = document.createElement("p");
                var link = document.createElement("a");
                link.onclick = function() {
                    openChat(friendsXML[i].textContent)
                };
                var friendText = document
                        .createTextNode(friendsXML[i].textContent + ":"
                                + statusXML[i].textContent);
                link.appendChild(friendText);
                friendListInDiv.appendChild(link);
                friendDiv.appendChild(friendListInDiv);
            }(i))
}

Your variables are getting hoisted to the outer scope, Javascript only has function level scoping.

David Xu
  • 5,555
  • 3
  • 28
  • 50