2016-11-23 65 views
0

這是我的代碼:如何觸發循環中創建的所有元素'onclick?

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> 
 

然而,當我點擊每個div, 「Hello World」 的始終顯示在最後div。 如何解決它?

回答

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>

+0

第一個解決方案能夠完成的工作,第二個解決方案觸發好奇:) – sabithpocker

+1

@sabithpocker - 搜索它...明白...這是[_cool_的事情...] (http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Rayon

+0

謝謝,但是,我試着把一些功能放入 cell.onclick = function(){ };但失敗.. –

相關問題