如何触发所有元素' onclick在循环中创建?

时间:2016-11-23 09:09:32

标签: javascript html

这是我的代码:



   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);
    }
&#13;
    <div id="left"></div>
  
&#13;
&#13;
&#13;

然而,当我点击每个div,&#34; Hello World&#34;始终显示在最后div上。 怎么解决它?

1 个答案:

答案 0 :(得分:4)

正在cell中分配loop的值,它将保留最后element的值

简单的解决方案:

在处理函数中使用this!在Event-handler函数中,this指的是调用了哪个事件的element

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>

或:使用closurereturned-function会记住创建它的环境!

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>