title: jQuery: Set click from array loop
body: <p>I have a series of divs in a pattern of header/body, where a click on the header will show the body in question.</p>
  
  <p>This all happens with .click initialized on page ready...</p>
  
  <p>Rather than doing this (which works fine, but is a pain):</p>
  
  <pre><code>$('#show_fold_ping').click(function(){ ShowArea('#fold_ping') });
  $('#show_fold_http').click(function(){ ShowArea('#fold_http') });
  $('#show_fold_smtp').click(function(){ ShowArea('#fold_smtp') });
  $('#show_fold_pop3').click(function(){ ShowArea('#fold_pop3') });
  ...
  </code></pre>
  
  <p>I am trying to do this:</p>
  
  <pre><code>var Areas = ['ping','http', 'smtp', 'pop3'];
  
  for( var i in Areas ){
      Area = '#show_fold_'+Areas[i];
      $(Area).click(function(){ alert(Area); /* ShowArea(Area); */ });
  }
  </code></pre>
  
  <p>The problem I'm having is that ALL of them seem to be initialized to the last one.  IE: If pop3 is the last one, a click on #show_fold_[any] will alert '#show_fold_pop3'.</p>
  
  <p>This seems like it should be really simple.  Am I missing something obvious, or is there an issue with passing a string to jQuery that I don't know about?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Hey, these are all great.  I have read up a bit on closures and self-invoking functions, and (kindasorta) get it.</p>
  
  <p>So far, I have this, but the click doesn't seem to be binding correctly.  Area will alert with the correct value, but no click bind.  Am I still having scope issues with Area, or am I just totally off mark?</p>
  
  <pre><code>$(function(){
  
      Areas = ['ping','http', 'smtp', 'pop3', 'imap', 'ftp', 'dns', 'tcp', 'database', 'seo'];
  
      for( var i = 0; i &lt; Areas.length; i++ ){
          (function (Area) {
                              alert(Area);
              $("#show_fold_"+Area).click(function(){ alert('x'); });
          })(Areas[i]);
      }
  });
  </code></pre>