Bind click handler with variables in scope when created?
<p>I'd like to create a list of items dynamically in jQuery, and dynamically bind a click handler to each one, with the variables in scope at the moment the click handler is created. </p>

<p>The code below creates a list of items from 1-6, but the click handler only seems to bind with the value of the final item - the alert always shows 6. </p>

<p>Is this a JavaScript scope problem? How can I bind the alerts with variables from 1-6?</p>

<p>HTML:</p>

<pre><code>&lt;ul id="saved-list"&gt;
&lt;/ul&gt;
</code></pre>

<p>JS:</p>

<pre><code>var all_cookies = [1,2,3,4,5,6];
for (var i = 0; i &lt; all_cookies.length; i++) {
    var route_num = all_cookies[i]; 
    var list_item = "&lt;li&gt;&lt;a href='#saved-route'&gt;";
    list_item += "&lt;p&gt;" + route_num + "&lt;/p&gt;&lt;/a&gt;&lt;/li&gt;";
    var newLi = $(list_item);
    newLi.bind('click', function(){
        alert(route_num);
    });
    $('#saved-list').append(newLi);      
}   
</code></pre>

<p>See jsFiddle here: <a href="http://jsfiddle.net/n6FU5/" rel="nofollow">http://jsfiddle.net/n6FU5/</a></p>
