2

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?

3
  • 2
    You should always use var for your loop variable, i.e. for (var row = 0; row < numOfRows; row++) Commented Apr 6, 2011 at 20:10
  • @Thief Always? I can think of a few examples where it would be useful to use a var that has been used elsewhere as the loop variable. Commented Apr 6, 2011 at 20:15
  • 1
    Well, at least unless it has been declared in the outer scope. What I wanted to say is that you should never make your loop variable global. Commented Apr 6, 2011 at 20:16

1 Answer 1

8
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.

Sign up to request clarification or add additional context in comments.

1 Comment

This seems perfect, it's exactly the sort of simple solution I was expecting there to be, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.