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

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 ?


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,