簡體   English   中英

如何觸發循環中創建的所有元素的onclick?

[英]How to trigger all of elements' onclick created in loop?

這是我的代碼:

  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 如何解決?

loop中分配cell值時,它將保存最后一個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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM