Help with Hyperlinks

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • beakersoft
    New Member
    • Aug 2007
    • 5

    Help with Hyperlinks

    Hi,

    This is my first attempt at trying to code using Ajax/Javascript so bear with me if i've missed something obvious.

    I'm trying to build a list of links in a div element based on info in an xml file. The problem is in my loop, everytime i create a link they all link to the last record of the xml file, and not the current one.
    I know i am looping though the XML ok because all the links have different names. This is the code:

    f
    Code:
    or (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.onclick = function () {getImage('placeHolder',picy)};
    
      					var linkText=document.createTextNode(picy);
      					newLink.appendChild(linkText);
      					document.getElementById('LinkList').appendChild(newLink);
      				}
    Its the newLink.onclick = function () {getImage('plac eHolder',picy)} ; that is causing the problem, the 'picy' variable is always being passed as the last xml record.

    The only thing i can think is happening is it's only writing out the last link, but i cant understand why
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Heya, beakersoft. Welcome to TSDN!

    The reason you are getting this behavior is because on this line:
    [code=javascript]
    newLink.onclick = function () {getImage('plac eHolder',picy)} ;
    [/code]

    You are creating a function that calls getImage(), with 'placeHolder' as the first parameter, and the variable picy as the second parameter.

    Note that as the loop iterates, the value of picy changes, and so all your functions ultimately do the same thing.

    Instead, you'll need to create a global object and assign elements based on the id of each link:
    [code=javascript]
    pices[i] = picy;
    newLink.id = i;
    newLink.onclick = function() { getImage('Place Holder', pices[this.id]); }
    [/code]

    Comment

    Working...