这是我的代码:
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;
然而,当我点击每个div
,&#34; Hello World&#34;始终显示在最后div
上。
怎么解决它?
答案 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>
或:使用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>