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.
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.
Is this a JavaScript scope problem? How can I bind the alerts with variables from 1-6?
HTML:
<ul id="saved-list">
</ul>
JS:
var all_cookies = [1,2,3,4,5,6];
for (var i = 0; i < all_cookies.length; i++) {
var route_num = all_cookies[i];
var list_item = "<li><a href='#saved-route'>";
list_item += "<p>" + route_num + "</p></a></li>";
var newLi = $(list_item);
newLi.bind('click', function(){
alert(route_num);
});
$('#saved-list').append(newLi);
}
See jsFiddle here: http://jsfiddle.net/n6FU5/