/    Sign up×
Community /Pin to ProfileBookmark

Creating links with onclick events in a loop

Hi,

I am having a problem and I really cant understand what’s happening. I am reading an XML file, and wanting to output links in a DIV based on what i get back. Part of the link i am creating needs to have an onClick event that will call another function.
Everytime I try and use any of the variables within my onClick (even the loop counter) it always returns the last value of the variable for all the records, ie if I have 3 records in the XML file, I can list three links but all 3 links will have the 3rd records information in there onClick event. This is the loop:

[CODE]for (var i=0; i < nodes.length; i++)
{
// Get the lastname element from our XML data document
var doc = xmlHttpObj.responseXML;
var lastName = nodes[i].nodeValue;
var node = doc.selectSingleNode(“//Customers/Customer[Lastname='” + lastName + “‘]”);
var picy = node.selectSingleNode(‘picture/text()’).nodeValue;

var newLink= document.createElement(‘a’);
newLink.setAttribute(‘href’, ‘#’);
newLink.setAttribute(‘onclick’, function(){ alert(“I’m Clicked: ” + i); });

var linkText=document.createTextNode(picy);
newLink.appendChild(linkText);
document.getElementById(‘LinkList’).appendChild(newLink);

}
[/CODE]

Its the onClick line i’m having problems with, can anyone suggest where i’m going wrong.

Cheers
Luke

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @beakersoft spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...