> On Dec 22, 12:55 am, "Michael Geary" <[EMAIL PROTECTED]> wrote: > By moving this code into a function, a new variable "i" is created each time > the function is called. You no longer have all the code sharing a single > variable - each instance of the function gets its own.
Ah, brilliant. I see that distinction/technique used a lot in jQuery. The fact that methods are first-class objects is incredibly powerful; I have yet to fully utilize it. Thanks for the help, Michael. :) --- On Dec 22, 12:55 am, "Michael Geary" <[EMAIL PROTECTED]> wrote: > As an alternative to the other solution you posted, here is how you can do > it with code more like the code below: > > for(var i = 0; i < 30; i++) > clicker( i ); > > function clicker( i ) { > jQuery('#day_' + i).click(function() { > console.log('i is ' + i); > jQuery('#day_' + i + '_modal').jqmShow(); > }); > > } > > As you can see, all I changed was to put your code inside a function and > call that function 30 times. > > Why did your original code show "i is 30" for each element? Because there is > only a single variable "i", and when you call console.log it's using the > current value of "i" - not the value that "i" had at the time you added the > click event. > > By moving this code into a function, a new variable "i" is created each time > the function is called. You no longer have all the code sharing a single > variable - each instance of the function gets its own. > > -Mike > > > From: Rabbit > > > The following code: > > > for(var i = 0; i < 30; i++) { > > jQuery('#day_' + i).click(function() { > > console.log('i is ' + i); > > jQuery('#day_' + i + '_modal').jqmShow(); > > }); > > } > > > Runs, but always reports "i is 30". > > > Now, I understand why it does that, but why doesn't the > > jqmShow method work? It appears as though the code that "gets > > executed" is dynamic. > > In other words, when the click event occurs JavaScript looks > > up the code as it was at the end of its execution, when > > variable i is 30, instead of "remembering" that at one point > > it was something else. > > > Did that make sense? > > > Any ideas how to get around this without typing in all 30 > > click events?