Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jan 2009
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

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

    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);

    }

  • #2
    New Coder
    Join Date
    Feb 2009
    Location
    Jakarta, Indonesia
    Posts
    93
    Thanks
    2
    Thanked 20 Times in 20 Posts
    Hi,

    U can give ap properties, like

    Code:
    var ap = document.getElementById('alink'+i);
    ap.href = "javascript:CallCustomer("+i+")";
    ap.icon = i;
    ap.onmouseover= function(){ 
    	t.innerHTML = "icon " + this.icon;
    };

  • Users who have thanked gun5 for this post:

    Blue_Crystal (02-03-2009)

  • #3
    Supreme Master coder! abduraooft's Avatar
    Join Date
    Mar 2007
    Location
    N/A
    Posts
    14,855
    Thanks
    160
    Thanked 2,223 Times in 2,210 Posts
    Blog Entries
    1
    Hi Blue_Crystal, pleas use [CODE][/CODE] tags to wrap your code while posting here. And you may highlight some specific parts using [ICODE][/ICODE] tags. You can use the shortcut buttons in the header of typing area to make it easier. ( and )

    Thanks.
    The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •