SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2007
    Posts
    50
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using variables in dynamically created functions

    Hello,

    I am trying to dynamically assign onclick events to elements on a page like so:

    Code:
    for(var i=1; i <= 5; i++){
      var p = i * 10;
      var el = document.getElementById("element-" + i);
      el.onclick = function(){ alert("Element value: " + p); };
    }
    I would have expected this to print out values of 10, 20, 30, 40, 50 but instead all elements print "Element value: 50". If i passed the var i directly instead of p in my alert function I might have understood this but does this mean that it keeps var p as the actual expression rather than just the result value? And then on the fly evaluates p = i * 10 using the last value assigned to i ?

    WOW!

    I know that I could get it to work using:

    element.onclick = new Function('alert("Element value: ' + p + '")');

    But I would prefer a more elegant solution. How can I force the current value of a variable in the loop to be used within the function where later invoked?


    Also, can someone point me to some document/article/discussion explaining the workings of Javascript here so that I know exactly what is going on and how to use it.


    Thank you,
    John

  2. #2
    SitePoint Guru
    Join Date
    Apr 2007
    Posts
    813
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you have to use closure binding.

    Code:
    getFunc = function (x) {
     var valX = x
    return function(){ alert("Element value: " + valX); };
    }
    
    for(var i=1; i <= 5; i++){
      var p = i * 10;
      var el = document.getElementById("element-" + i);
      el.onclick = getFunc(p)
    }


Bookmarks

Posting Permissions

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