[英]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>
或者:使用closure
, returned-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.