2

I am trying to make a cell in a table tell me its number when I click it.

for(var j = 0; j < 8; j++){
    var cell = row.insertCell(j);
    cell.name = j;
    cell.onclick=function(){alert(cell.name)};
}

This however, prints the number 8 for every cell. How do I save the value of j in cell.name, instead of just having it point to the variable j?

Thanks.

7
  • 2
    But going off your code, your cell reference appears to be constant? Commented Sep 2, 2013 at 11:14
  • 1
    Where do you initialize cell? Commented Sep 2, 2013 at 11:15
  • If you have only one cell, this isn't going to work. Commented Sep 2, 2013 at 11:15
  • Change cell so it points to different cells in each iteration. Commented Sep 2, 2013 at 11:15
  • I have added the "var cell = row.insertCell(j);" Think that is what you ment? Commented Sep 2, 2013 at 11:29

1 Answer 1

5

IMPORTANT: All JavaScript developers should know this. It will cause all kinds of weird bugs that is very hard to find.

It is a common mistake of people who are new to JavaScript. I've made the same mistake before.

A function inside a loop is NOT created for every iteration. It is the same one function object with the same closure scope. Thus, your cells will have the exact same onclick callback.

My advice here is NEVER EVER create a function inside of loop. Instead, create and call a function that returns a callback function and assign it to onclick.

for (var j = 0; j < 8; j++) {
    var cell = row.insertCell(j);
    cell.name = j;
    cell.onclick = createOnClick(cell);
}

function createOnClick(cell) {
    return function () {
        // do whatever you want to do with cell
    };
}
Sign up to request clarification or add additional context in comments.

3 Comments

Something like this? function a(name) { function b(name){ alert(name); } return b(); }
I will give you an example in few minutes once I turn on my laptop.
This worked. I placed the "alert(cell.name)" inside the returned function and it now work as intended. Thanks alot :)

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.