I have a for loop running in javascript. In this loop I am creating a list item and binding a click event to it. When I click this list item I want it to call a function with the data from the current loop object as a parameter.
The problem is, no matter what list item I click. The data that is being passed as the parameter is the last element of the object I am looping rather than the current one that is being clicked.
for(e in data) {
var suggestItem = $('<li>'+ data[e]['name'] +'</li>');
suggestItem.click(function() {
$(this).addClass('activeSuggestion');
suggestSelect(suggestField, data[e]);
});
suggestList.append(suggestItem);
}
I think I understand why this happens but not sure how I should handle it.
You need to break the closure over
e.Since you’re using jQuery, the easiest way would be to save the current value of
ewith jQuery’sdatafunction. Since all function parameters in JavaScript are passed by value, this effectively breaks the closure; now your click handler will work with what the value ofeis when the handler was created, and not the valueeholds when the loop ends.