Reputation: 723
This should be quite a simple problem, I've come across it enough that there should be an obvious solution, but I think I'm struggling to phrase it right.
I'm running a loop in JS/jQuery that binds functions to events for certain elements. As the elements are dynamically added to the page, I want the function to contain a reference to the specific element it will be modifying. A simplified example is shown below, along with the workaround code I'm using.
for (row = 0; row < numOfRows; row++) {
$('#row' + row + ' input').keyup(function () {
alert($(this).parent().parent().get(0).id);
});
}
The issue here is that in order to get a reference to the row, rather than using the variable being used in the loop, I have to pull the reference out of the row's ID in a long winded fashion (in the code above, there's then be another line that strips "row" from the identifier, omitted for clarity.)
What I'd like to work is something similar to:
for (row = 0; row < numOfRows; row++) {
$('#row' + row + ' input').keyup(function () {
alert(row);
});
}
However, this obviously only returns the ID of the last element to be added. I'm sure there's a simple way of just taking the value of the variable rather than a reference to it, but I just haven't come across it yet. Can anyone help?
Upvotes: 2
Views: 307
Reputation: 318518
for (var row = 0; row < numOfRows; row++) {
(function(row) {
$('#row' + row + ' input').keyup(function() {
alert(row);
});
})(row);
}
This creates a new closure and since the row is passed as a function argument it's "detached" from the loop variable.
Upvotes: 8