title: javascript each uses last variable value
body: <p><a href="https://jsfiddle.net/12xmodp9/1/" rel="nofollow noreferrer">https://jsfiddle.net/12xmodp9/1/</a></p>
  
  <p>When doing each with jquery, how do I use the number selected each time?</p>
  
  <p>eg. in this case I would expect the alert to display the number of the element clicked on.</p>
  
  <pre><code>&lt;div id="foo"&gt;&lt;/div&gt;
  &lt;script type="text/javascript"&gt;
  for (i = 0; i &lt; 20; i++) {
      $('#foo').append(
          $('&lt;a&gt;',
              {href: '#',
              id: "foo_" + i,
              html: i 
              }).on("click", function(){alert(i)})
      );
  }
  &lt;/script&gt;
  </code></pre>
  
  <p>Instead it always displays "20"</p>