Creating unique click events with a loop
I am working on an AJAX calendar program, and I would like to be able to apply click events to divs within the different days of the calendar with a loop.
Here is a very simple version of the type of code I am trying to write:
-
$(document).ready(function(){
for( x=1; x <= 5; x++ ) {
$('#d' + x).click( function(){
alert(x);
});
}
});
Now, in this example if I have a bunch of divs all named #d1, #d2, #d3, etc what I would
like this code to do is to apply a click event that causes an alert to come up with the appropriate number. So clicking on #d3 should cause an alert that says "3". What
actually happens is that when you click on one of the divs, it alerts the last value assigned the variable. So if I clicked on #d3 it would alert "5". Indeed, every div affect by my loop would alert "5".
Now, in the final version I would be doing something more complicated than alerting a number -- I would instead be accessing data from an array. However the principle should be the same.
If anyone could give me a suggestion, I would greatly appreciate it.