title: Click Event Closure Inside Loop
body: <p>I have a click event attached to an element via JQuery in a loop (loop variable i):</p>
  
  <pre><code>$('#id_'+i).click(function() {ItemClick(i)});
  </code></pre>
  
  <p>And defined somewhere else:</p>
  
  <pre><code>function ItemClick(x) {
      alert(x);
  }
  </code></pre>
  
  <p>As expected, this doesn't work as expected, because of the closure. I'd like to see a different number shown for each different click event, instead I just get the last value of i. </p>
  
  <p>I know I need to turn the i in the closure to something that somehow isn't attached to the scope of the closure, but it eludes me, even after trying various examples. Such as:</p>
  
  <pre><code>$('#id_'+i).click(function() {ItemClick(function(x){return x)(i))});
  </code></pre>
  
  <p>Is there a neat and concise way of doing this?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>After looking at the duplicate, I now have two answers (please close the question):</p>
  
  <p><em>Answer A</em></p>
  
  <pre><code>$('#id_'+i).data('index',i);
  
  $('#id_'+i).click(
      function() {
          ItemClick($(this).data('index'));
      }
  );
  </code></pre>
  
  <p><em>Answer B</em></p>
  
  <pre><code>$('#id_'+i).click(
      function(index) {
          return function () {
              ItemClick(index)
          };
      }(i)
  );
  </code></pre>