[jQuery] Dynamically added "click" registration always returns the last value added
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