applying an event handler to newly created objects

后端 未结 3 1927
星月不相逢
星月不相逢 2021-01-29 03:14

So my goal is to have 5 boxes and every time one box is clicked a new box appears. The code I wrote for that is this:

window.onload = function(){
    var boxLis         


        
3条回答
  •  不要未来只要你来
    2021-01-29 03:31

    box.onclick = clickHandler;
    

    There are more elegant ways, but as that's what you're already doing, there's no harm doing what you're doing, now.

    In a different world, you might do something like:

    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");
      }
    }
    

    I don't have to worry about further click-handling beyond that, if all of the boxes are descendants of #master. makeNewBox here is simply separating the creation of the object from what you actually want to do with it.

提交回复
热议问题