【发布时间】:2015-12-01 23:21:43
【问题描述】:
所以我的目标是拥有 5 个框,每次单击一个框时都会出现一个新框。我为此编写的代码是这样的:
window.onload = function(){
var boxList = document.getElementsByClassName("box");
for(i = 0; i< boxList.length;i++){
boxList[i].onclick = clickHandler;
}
}
function clickHandler(eo){
if(eo.target.style.backgroundColor != "black") {
eo.target.style.backgroundColor = "black";
var box = document.createElement("div");
box.setAttribute("class","box");
box.setAttribute("id",document.getElementsByClassName("box").length++);
document.getElementById("Master").appendChild(box);
}
else eo.target.style.backgroundColor = "white";
}
所有 div 的类都是“盒子”,我只是为每个新盒子添加一个新 id。我的问题是事件处理程序似乎不适用于新创建的框。怎么可能解决?
非常感谢!
【问题讨论】:
-
添加 box.onclick = clickHandler;在 document.getElementById("Master").appendChild(box); 之后。这是因为您没有将 onclick 处理程序分配给新对象。
-
我认为您的事件处理程序正在工作,我使用了您的代码并将警报放入
clickHandler并且那些弹出了.. 我认为您的问题是其他问题,可能是框重叠,请放您的 HTML 代码也是如此 ..