for loop and dynamic events

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ciary
    Recognized Expert New Member
    • Apr 2009
    • 247

    #1

    for loop and dynamic events

    Hi all,

    i've got another problem. it's based on the question i asked before about creating a onclick-property using javascript.

    now what i want to do is create multiple divs with an onclick-property using a for-loop and a 2D array.

    Code:
    for(var m = 0; m < inputdivs.length; m++){
    	var arr = inputdivs[m];
    	var newd = document.createElement("div");
    
    	newd.innerHTML = arr[0];
    	newd.style.width = arr[1];
    	newd.style.height = arr[2];
    	newd.style.top = arr[3];
    	newd.style.left = arr[4];
    	newd.style.position = "absolute";
    	newd.style.fontWeight = arr[5];
    	newd.style.fontStyle = arr[6];
    	newd.style.color = arr[7];
    	newd.style.textDecoration = arr[8];
    	newd.style.fontSize = arr[9];
    	newd.style.textAlign = arr[10];
    	newd.style.verticalAlign = arr[11];
    	newd.id = arr[12];
    	newd.style.border = "solid 1px #BBBBBB";
    	newd.onclick = function(){myFunct(arr[12])};
    	newd.onmouseup = function(){myProb(arr[12])};
    
    	$("foo").appendChild(newd);                    //this is prototype meaning document.getelementbyid()
    }
    problem is, the onclick always sends the value of the last created div rather then the value of the div i've clicked on. the strange thing is that all other properties are added fine.

    does anyone know whats causing this and how to fix it?
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    could be a Closure*. I could tell you more, if I knew what the two functions in the events are doing.

    * see this thread

    Comment

    • Ciary
      Recognized Expert New Member
      • Apr 2009
      • 247

      #3
      Originally posted by Dormilich
      e.g.
      Code:
      element.parameter = i;
      element.onmouseover = function() { alert(this.parameter); }
      this worked. but i found out if you use element.paramet er instead if this.parameter, you encounter the same problem as not i noted above. so the 'this' is very important

      anyway, ty Dormilich. i dont know what i would have done without this :)

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        Originally posted by Ciary
        but i found out if you use element.paramet er instead if this.parameter, you encounter the same problem as not i noted above.
        of course, element is the/one variable preserved by the Closure.

        rule of thumb: if the passed value is fixed (like a string or a number) there's no problem with closures. care is to be taken if the closure appears in a loop.

        besides that using "this" is much cooler (*g*) and efficient, once you understand it.

        Comment

        Working...