0

This is my code:

   var board = document.getElementById("left");
    for (var m = 0; m < 5; m++) {
        var cell = document.createElement('div');
        cell.className = "Cell";
        cell.style.cssText='background-color:#999999;margin:5px;width:50px;height:100px;';
        cell.onclick= function() {
                    cell.innerHTML = "Hello World";
            };
        cell.name = m;
        board.appendChild(cell);
    }
    <div id="left"></div>
  

However, when I click every div, "Hello World" always show on the last div. How can fix it?

Manish Patel
  • 3,648
  • 1
  • 14
  • 22
張麥可
  • 5
  • 4

1 Answers1

4

As value of cell is being assigned in the loop, it will hold the value of last element

Simple solution:

Use this in handler function! In Event-handler function, this refers to element on which event is invoked!

var board = document.getElementById("left");
for (var m = 0; m < 5; m++) {
  var cell = document.createElement('div');
  cell.className = "Cell";
  cell.style.cssText = 'background-color:#999999;margin:5px;width:50px;height:100px;';
  cell.onclick = function() {
    this.innerHTML = "Hello World";
  };
  cell.name = m;
  board.appendChild(cell);
}
<div id="left"></div>

Or: Use closure, returned-function remembers the environment in which it is created!

var board = document.getElementById("left");
for (var m = 0; m < 5; m++) {
  var cell = document.createElement('div');
  cell.className = "Cell";
  cell.style.cssText = 'background-color:#999999;margin:5px;width:50px;height:100px;';
  cell.onclick = (function(cell) {
    return function() {
      cell.innerHTML = "Hello World";
    }
  })(cell);
  cell.name = m;
  board.appendChild(cell);
}
<div id="left"></div>
Rayon
  • 36,219
  • 4
  • 49
  • 76