Ive got a problem with the following loop:
for (var i = 0; i < dataElements; ++i){
d=document.createElement('div');
$(d).addClass('overviewbit')
.appendTo('.overview')
.click(function(){
id = i;
});
}
Every Div sets id to the highest value of the loop but i should be the exact value i gets when its created. So the first div should set it to 1, the second div should set it to 2 and so on. i hope you understand my problem and could help me to find a solution.
This a common problem. When you create the
clickhandler, it’s settingidtoi— the variable, not the valueiwas storing at the time.The
forloop is completing before any of the DIVs are clicked, soiis equal to the final value from the loop for all the click handlers, and as a result all theids are set to the same value.With jQuery you can solve this problem by using
.data()storage:However, to do things the “proper” way you would use a JavaScript closure: