I have something like this:
var a = {
generateDynamicStuff: function(data) {
for(var i=0;i<data.length;i++) {
var dyn_div = document.createElement('div');
dyn_div.className = "dyn_div_"+data[i].name;
dyn_div.textContent = data[i].name;
document.getElementByClassName("dyn_list")[0].appendChild(dyn_div);
$(document).on("click", ".dyn_div_"+data[i].name, function() { alert(i); a.otherFunction(i);});
}
},
otherFunction: function(some_index) {....}
}
The idea is, I am given a list of names which I will generate clickable div elements with. When one of these divs are clicked, its index will be passed to otherFunction().
The problem is, function() { alert(i); a.otherFunction(i);} always gives the last index. That is, if I have 5 items, then i in the anonymous function is always giving me "4" no matter which div I am clicking.
Why is this?