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

标签 javascript eventhandler

所以我的目标是有 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/

相关文章:

javascript - 如何在indexedDB中执行 "select * from table where indexA >= ' a' order by indexB ASC limit 10"?

Javascript 减法返回 NaN

coldfusion - cfschedule : Fire onError function if url cannot be found

JavaScript 事件监听器与事件处理程序

javascript - 绑定(bind)和事件处理程序——传递事件对象

javascript - ajax 购物车成功隐藏 div 并显示另一个

php - TinyMCE : How to insert snippets in editor which will be replaced by plain PHP?

javascript - 克隆表行

eventhandler - 为什么 lmax 干扰器架构使用 2 个干扰器?

javascript - 效率 : one event handler or multiple