Problem found on creating elements dynamically in a “for” loop

Discussion in 'JavaScript' started by Blue_Crystal, Feb 2, 2009.

  1. #1
    In the below code, the created link element (ap) correctly displays the right customer number in the instruction “ap.href="javascript:CallCustomer("+i+")";” but it displays the wrong icon number in the instruction “ap.onmouseover= function(){ t.innerHTML = "icon " + i};”. It always shows the last value of “i” in the for loop plus 1, no matter what link the mouse is over.

    How to fix it ?



    function init()
    {

    t = document.getElementById("test");

    ctn = document.getElementById('container');

    for( var i= 0; i < total_icons; i++)
    {
    var newdiv = document.createElement('div');
    var divIdName = 'icon_pos'+i;
    newdiv.setAttribute('id',divIdName);

    ctn.appendChild(newdiv);

    var alink = document.createElement('a');
    var aIdName = 'alink'+i;
    alink.setAttribute('id',aIdName);

    newdiv.appendChild(alink);

    var ap = document.getElementById('alink'+i);

    ap.href = "javascript:CallCustomer("+i+")";

    ap.onmouseover= function(){ t.innerHTML = "icon " + i};


    var icon_img = document.createElement('IMG');

    var imIdName = 'icon'+i;

    icon_img.setAttribute('id', imIdName);

    alink.appendChild(icon_img);

    }

    //...

    }

    function CallCustomer( number )
    {
    alert("You called Customer "+number);

    }
     
    Blue_Crystal, Feb 2, 2009 IP
  2. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Yep, it will. Because you create a new function this function uses the global scope, where i is the same as used in the for loop, which by the time of the mouseover event, has the last value from the for loop condition. The simplest solution is to put the onmouseover function outside the for and call it like you call CallCustomer(), with the current value of i. Something like that:

    ap.onmouseover= "javascript: mOver("+i+")";
    Code (markup):

    and then you have

    
    function mOver(value)
    {
       document.getElementById('test').innerHTML = "Icon "+value;
    }
    
    Code (markup):
    somewhere in the code..
     
    xlcho, Feb 3, 2009 IP
  3. Blue_Crystal

    Blue_Crystal Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you, xlcho.
     
    Blue_Crystal, Feb 3, 2009 IP