如果您在window.onload
处理程序已经运行后动态创建框,那么您将不得不在这些动态创建的框上运行一些附加代码,这些代码在创建后为其分配点击处理程序。
function clickHandler(eo){
if(eo.target.style.backgroundColor != "black") {
eo.target.style.backgroundColor = "black";
var box = document.createElement("div");
box.setAttribute("class","box");
// add this line of code to assign the click handler
box.onclick = clickHandler;
box.setAttribute("id",document.getElementsByClassName("box").length++);
document.getElementById("Master").appendChild(box);
}
else eo.target.style.backgroundColor = "white";
}
或者,你可以使用委托事件处理和处理来自未动态创建一个共同的父的事件。
委托的事件处理使用“事件冒泡”,事件冒泡其父链,使您可以附加一个单击处理程序,以一个共同的父,然后检查e.target
在单击处理程序,以查看是否发生在你的盒子要素之一点击然后处理它一个地方。在动态添加内容的情况下,这可以很好地工作。
委派的事件在你的代码中处理会是这个样子:
window.onload = function(){
// put click handler on common box parent and use event bubbling
document.getElementById("Master").addEventListener("click", clickHandler);
}
function clickHandler(eo){
// if this click occurred on one of my boxes
if (hasClass(eo.target, "box"))
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";
}
}
// utility function for checking a class name
// could also use .classList with a polyfill for older browsers
function hasClass(elem, cls) {
var str = " " + elem.className + " ";
var testCls = " " + cls + " ";
return(str.indexOf(testCls) !== -1) ;
}
添加box.onclick = clickHandler事件; after document.getElementById(“Master”)。appendChild(box);.这是因为您没有将onclick处理程序分配给新对象。 – NPToita
我认为你的事件处理程序正在工作,我使用你的代码并将警报放在'clickHandler'里面,并且这些都在弹出。我认为你的问题是别的,可能是盒子重叠,请放上你的HTML代码。 – hagrawal