Wow, thanks very much. It worked like a charm.
I hadn't used the $.each function in jQuery yet, so thank you for pointing
me to it. I suspect I'll be using it a lot more now that I know how to!
Chad
Michael Geary wrote:
>
> You're using the variable "j" to hold a reference to each element of the
> jobs array as you go through the loop. After the loop finishes, "j" is a
> reference to the last element of that array.
>
> Later, when the click function gets called, "j" still refers to that last
> element - regardless of which element triggers the event.
>
> You need to keep track of each of those elements separately. The easiest
> way
> to do that is with a closure.
>
> Also, you don't want to use "for in" to iterate over an array. Use a
> C-style
> loop instead. So, you could code this:
>
> for( var i = 0, n = json.jobs.length; i < n; i++ ) {
> (function( job ) {
> // ...
> $("#editJob" + job.jobID).click(function() {
> alert(job.jobID);
> });
> })( json.jobs[i] );
> }
>
> The inner function captures a separate "job" variable for each instance of
> the loop, so when the click function gets called later, it will have the
> correct reference. (I took the liberty of changing the name from j to job
> just to make the example more clear - I always think of "j" as an index
> variable like "i".)
>
> Even better, jQuery has an iterator function you can use to simplify the
> code:
>
> $.each( json.jobs, function( i, job ) {
> // ...
> $("#editJob" + job.jobID).click(function() {
> alert(job.jobID);
> });
> });
>
> Again, each click function will use its own copy of the job variable - not
> because of any jQuery magic, but simply because of the use of the inner
> function. $.each just runs the loop for you.
>
> -Mike
>
>
--
View this message in context:
http://www.nabble.com/Dynamically-added-%22click%22-registration-always-returns-the-last-value-added-tf2812575.html#a7849617
Sent from the JQuery mailing list archive at Nabble.com.
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/