无法将 javascript eventListener 添加到最近创建的元素

Cannot add javascript eventListener to recently created element

我使用 Javascript 创建了 625 <div class="box"><div> 然后我想为每个盒子添加事件侦听器。框已成功创建,但侦听器不工作。这是我的完整代码,非常感谢您的所有回复。谢谢

<!DOCTYPE html>
<html>
<head>
    <title>Number AI | Machine Learning Technologhy</title>
    <style>
        .box-container{
            display: grid;
            width: 300px;
            height: 300px;
            border: 1px solid blue;
            grid-template-columns: auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto;
        }
        .box{
            width:10px;
            height:10px;
            border: 1px solid black;
            text-align: center;
        }
    </style>
    <script type="text/javascript">
        function initiateBox(){
            for (let i = 0; i < 625; i++) {
                let box = document.createElement("DIV");
                box.classList.add("box");
                document.querySelector('.box-container').appendChild(box);
            }
        };
        window.onload = initiateBox;
    </script>
</head>
    <body>
        <h2>Number AI</h2>
        <div class="box-container"></div>
        
        <script>
            document.querySelectorAll(".box").forEach(box =>{
                box.addEventListener("mouseover",function(){
                    box.style.backgroundColor = 'black';
                });
            });
        </script>
    </body>
</html>

几件事

  1. 在加载和鼠标悬停时使用 addEventListeners
  2. 委托,这样您就可以在容器存在后随时创建盒子
  3. 也许 CSS 悬停是执行此操作的实际方法?

无论如何,这是委托脚本

function initiateBox() {
  const container = document.querySelector('.box-container');
  for (let i = 0; i < 625; i++) {
    let box = document.createElement("div");
    box.classList.add("box");
    container.appendChild(box);
  }

  container.addEventListener("mouseover", function(e) {
    const tgt = e.target;
    if (tgt.classList.contains("box")) tgt.style.backgroundColor = 'black';
  });
};
window.addEventListener("load",initiateBox)
.box-container {
  display: grid;
  width: 300px;
  height: 300px;
  border: 1px solid blue;
  grid-template-columns: auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto;
}

.box {
  width: 10px;
  height: 10px;
  border: 1px solid black;
  text-align: center;
}
<title>Number AI | Machine Learning Technologhy</title>

<h2>Number AI</h2>
<div class="box-container">
</div>

好吧,这里有多种选择。但是最简单的 (效率不高) 是在盒子创建时添加事件监听器,如下所示:

<!DOCTYPE html>
<html>

<head>
  <title>Number AI | Machine Learning Technologhy</title>
  <style>
    .box-container {
      display: grid;
      width: 300px;
      height: 300px;
      border: 1px solid blue;
      grid-template-columns: auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto;
    }
    
    .box {
      width: 10px;
      height: 10px;
      border: 1px solid black;
      text-align: center;
    }
  </style>
  <script type="text/javascript">
    function initiateBox() {
      for (let i = 0; i < 625; i++) {
        let box = document.createElement("DIV");
        box.classList.add("box");
        box.addEventListener("mouseover", function() {
          box.style.backgroundColor = 'black';
        });
        document.querySelector('.box-container').appendChild(box);
      }
    };
    window.onload = initiateBox;
  </script>
</head>

<body>
  <h2>Number AI</h2>
  <div class="box-container"></div>
</body>

</html>

但无论如何,如果您正在寻找一种有效的方法来执行此操作,正如@mplungjan 在评论中指出的那样,最好使用 delegation 方法,如下所示:

<!DOCTYPE html>
<html>

<head>
  <title>Number AI | Machine Learning Technologhy</title>
  <style>
    .box-container {
      display: grid;
      width: 300px;
      height: 300px;
      border: 1px solid blue;
      grid-template-columns: auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto;
    }
    
    .box {
      width: 10px;
      height: 10px;
      border: 1px solid black;
      text-align: center;
    }
  </style>
  <script type="text/javascript">
    function initiateBox() {
      const boxContainer = document.querySelector('.box-container');
      for (let i = 0; i < 625; i++) {
        let box = document.createElement("DIV");
        box.classList.add("box");
        boxContainer.appendChild(box);
      }

      boxContainer.addEventListener("mouseover", function(event) {
        const target = event.target;
        if (target.classList.contains('box'))
          target.style.backgroundColor = 'black';
      });
    };
    window.onload = initiateBox;
  </script>
</head>

<body>
  <h2>Number AI</h2>
  <div class="box-container"></div>
</body>

</html>

我认为第二个脚本是 运行 在将框元素附加到文档之前,因此没有找到任何框。您可以将 eventListener 添加到您创建的 initiateBox 函数中,如下所示:

function initiateBox(){
        for (let i = 0; i < 625; i++) {
            let box = document.createElement("DIV");
            box.classList.add("box");
            box.addEventListener("mouseover",function(){
                box.style.backgroundColor = 'black';
            });
            document.querySelector('.box-container').appendChild(box);
        }
    };
    window.onload = initiateBox;

如果背景颜色实际上是 属性 您要在 mouseOver 上更改的颜色,我建议使用 CSS 悬停。