Variables in click handler

Variables in click handler

When using variables in click handlers, is there a way to use the value of the variable when the handler was set instead of run?  For example:

  1. var links = new Array;
  2. for (i = 0; i < 5; i++) {
  3.   links[i] = document.createElement('span');
  4.   $("body").append(links[i]);
  5.   $(links[i]).text("Click here!");
  6.   $(links[i]).click(function() {
  7.     alert(i);
  8.   });
  9. }
All five of the "Click here!" create an alert with the number 5, which was the last value i was.  How can I have each click function use the value of i when it was looping through (0, 1, 2, 3, 4)?  Thanks!