如果您在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