title: Onclick adds to last element in loop only
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/4091765/assign-click-handlers-in-for-loop">Assign click handlers in for loop</a>  </p>
  </blockquote>
  
  
  
  <p>I need help with a loop in my code.</p>
  
  <p>I loop through an array and add on clicks to divs. But it always adds onclicks to the last cycle through the loop and effectively cancels out the ones before it.</p>
  
  <p>So i have this as my loop:</p>
  
  <pre><code>    start = 0;
  
  for(i = start; i &lt; (start+8); i++){ //8 per page
      if(i == array.length){ 
          break;  //page end
      } else {
          (function(i){
               document.getElementById('cell'+i).onclick = function(){ select(i); }
          })(i);  
      }
  }
  </code></pre>
  
  <p>What occurs here is div id <code>cell7</code> gets the on click added, but the div ids <code>cell0</code> to <code>cell6</code> do not. I'm guessing its something to do with the fact that <code>i</code> changes in the loop and so is also effected the <code>i</code> in the function ?</p>
  
  <p>How do I fix this problem ?</p>