title: Javascript -- Attach events in loop
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8909652/adding-click-event-listeners-in-loop">adding ‘click’ event listeners in loop</a>  </p>
  </blockquote>
  
  
  
  <p>I make a demo.So let's see the HTML first.</p>
  
  <pre><code>&lt;a href="#" id="testA"&gt;testA&lt;/a&gt;
  &lt;a href="#" id="testB"&gt;testB&lt;/a&gt;    
  
  &lt;div id="showA"&gt;showA&lt;/div&gt;
  &lt;div id="showB"&gt;showB&lt;/div&gt;
  </code></pre>
  
  <p>And i want to bind <code>click</code> events to Elements <code>a</code> . and when it clicks, <code>alert</code> the related <code>div</code>. (click <code>id="testA"</code>,alert <code>id="showA"</code> ...)</p>
  
  <p>And i write the jQuery code.</p>
  
  <pre><code>var arr = ["A","B"];    
    for(var i=0;i&lt;arr.length;i++){
      $("#test"+arr[i]).click(function(){
        alert($("#show"+arr[i]).text())
      });
    }
  </code></pre>
  
  <p>But it doesn't work. I debug this code and find that this code <code>alert($("#show"+arr[i]).text())</code></p>
  
  <p>only run when I click the <code>a</code> element . and when I click <code>a</code> . the variable <code>i</code> is <code>3</code> already.</p>
  
  <p>So what should I do?</p>