javascript dynamic function problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chathura86
    New Member
    • May 2007
    • 227

    javascript dynamic function problem

    Code:
    			for (i = 0; i <= 30; i++)
    			{
    				var obj = 'date_' + i;
    				document.getElementById(obj).onmouseover = function (event) { alert(i) };
    			}
    date_1, date_2, date_3, ........., date_30 are hyperlink with those ids

    i have added the above javascript to show the date on mouse over but no matter which date I go mouse over, it shows 30, and when i set i <= 10 it shows 10
    i think it shows the final value of i,

    please help me to fix it.

    Regards
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    what happened here is (in my opinion) that you incidentally run into a Closure. (this happens when you define a function inside another function or if events are incorporated) the interesting point is, that local variables (here i) are preserved.

    Comment

    • chathura86
      New Member
      • May 2007
      • 227

      #3
      Thanks for the responce

      any idea how to fix it?

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        e.g.
        Code:
        element.parameter = i;
        element.onmouseover = function() { alert(this.parameter); }
        some more advanced one
        Code:
        element.parameter = i;
        var show = function() { alert(this.parameter); }
        element.addEventListener("mouseover", show, false);
        // or use the appropriate cross-browser solution
        Last edited by Dormilich; Apr 12 '09, 07:51 AM. Reason: added Event Listener

        Comment

        Working...