I'm currently running into a problem where I dynamically create a set of divs and, while creating them, I assign an onclick() event to them. A simplified version of the code looks like this:
for(DayOfTheWeek = 0; DayOfTheWeek < 7; DayOfTheWeek++){
var EventCell = document.createElement('div');
var EventDayIndex = WeekNumber*7 + DayOfTheWeek + EventoDayOffset;
EventCell.onclick = function(){ClickableDivFunction(EventDayIndex)};
}
The problem I have is that all my set of divs call ClickableDivFunction using the argument of the final EventDayIndex calculated. This is All my 7 divs execute ClickableDivFunction(6) instead of my first div executing ClickableDivFunction(0), the second ClickableDivFunction(1) and so on.
While searching on this forum I found the following answer which explains my problem. Basically EventDayIndex will not just evaluate and leave the value it got on every iteration in the function defined for the onclick event.
I tried several things such as trying to cast EventDayIndex into a string hoping the argument of ClickableDivFunction would keep its value. Trying to add another variable, generating a string using '+' operator and then adding a filter to ClickableDivFunction to remove the extra text (This is I was trying to force the evaluation of EventDayIndex by doing:
var NewVar = ClickableDivFunction + "#";
and then removing the "#" in the calling function.) In all cases I got the same result. So my question is, how would you guys recommend to solve this problem in a safe, maintainable way? I'd assume people would have encountered this problem in the past and I just don't have enough knowledge in programming to know what to search for but all the things I could think to solve this problems were either, casting to text or finding a way to make an variable assignment by value.
I'd appreciate any help on this or a link to the answer.