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.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
stefan
  • 195
  • 1
  • 13

1 Answers1

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
    };
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Joon
  • 9,346
  • 8
  • 48
  • 75
  • Something like this? function a(name) { function b(name){ alert(name); } return b(); } – stefan Sep 02 '13 at 11:27
  • I will give you an example in few minutes once I turn on my laptop. – Joon Sep 02 '13 at 11:29
  • This worked. I placed the "alert(cell.name)" inside the returned function and it now work as intended. Thanks alot :) – stefan Sep 02 '13 at 11:44