jQuery element binding is delayed, how to avoid it?
<p>I am trying to create a few elements &amp; then bind them to different methods, e.g., </p>

<pre><code>for( key in object ){
  var vals = someMap[key];
  var element = jQuery(parentElements[key]).find('.someClass');
  var markup;
  for( someKey in vals ){
      markup += "&lt;a href='#' &gt;" + vals[someKey] + "&lt;/a&gt;";
  }
  jQuery(element).empty().html(markup);
  jQuery(element).find('a').bind('click', function(element){ alert(key); });
}
</code></pre>

<p>Now after running this code, I am able to create all the anchor elements, and so the alert should print the key within which the anchor tags were created, e.g., if I had 2 keys key1 &amp; key2, so anchor tags were created inside the parentElements[key1] &amp; parentElements[key2], so whenever I click on an anchor tag, I should have got alerted with either key1 or key2, depending on whose anchor tag i clicked. But the problem is that always key2 is alerted. So , I am thinking that the issue here might be that the binding is delayed till a click is performed, and when it is performed, the value of key alerted would always be the last key, i.e., key2.
I am not very sure what the issue here is, but since its always the last key being alerted, I have an impression that the binding is happening at the end, when both the loops have completed.</p>

<p>So is there something I am doing wrong, or should I do it in a different way? Any help appreciated.(maybe the question is not very explanatory, please let me know incase I should replace it with something else).</p>
