gpt4 book ai didi

javascript - 将事件处理程序应用于新创建的对象

转载 作者:行者123 更新时间:2023-12-03 08:13:54 25 4
gpt4 key购买 nike

所以我的目标是有 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 的类都是“box”,我只是向每个新框添加一个新的 id。我的问题是事件处理程序似乎不适用于新创建的框。怎么解决呢?

非常感谢!

最佳答案

box.onclick = clickHandler;

还有更优雅的方法,但由于这就是您已经在做的事情,所以现在做您正在做的事情没有什么坏处。

在不同的世界中,您可能会这样做:

var master = document.querySelector("#master");

master.addEventListener("click", clickHandler);

function clickHandler (e) {
var box = e.target;
var newBox;
var totalBoxes = master.querySelectorAll(".box").length;
if (!box.classList.contains("box")) {
return; // not a box
}

if (isBlack(box)) {
changeColour(box, "white");
} else {
newBox = makeNewBox(totalBoxes + 1);
master.appendChild(newBox);
changeColour(box, "black");
}
}

如果所有框都是#master 的后代,我不必担心除此之外的进一步点击处理。makeNewBox 这里只是将对象的创建与您实际想要用它执行的操作分开。

关于javascript - 将事件处理程序应用于新创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com