简体   繁体   English

如何为 div 元素添加事件监听器?

[英]How to add event listeners to div elements?

I want to add an event listener to each of the div elements with the class "box" here:我想在此处使用 class“框”向每个 div 元素添加一个事件侦听器:

<div class="gameBox">
            <div class="msgs">
                <p class="msg">Click in a box to play. Crosses start.</p>
            </div>
            <div class="gameTable">
                <div class="box" id="0"></div>
                <div class="box" id="1"></div>
                <div class="box" id="2"></div>
                <div class="box" id="3"></div>
                <div class="box" id="4"></div>
                <div class="box" id="5"></div>
                <div class="box" id="6"></div>
                <div class="box" id="7"></div>
                <div class="box" id="8"></div>
            </div>
            <div class="reset">Reset</div>
        </div>
let elementsArray = document.querySelectorAll(".box");

elementsArray.forEach(function(div) {
    div.addEventListener("click", function() {
        alert("AA");
    });
});

This is the JavaScript I have used to do this, however it does not return anything.这是我用来执行此操作的 JavaScript,但它不返回任何内容。 I think the issue may be that the div element is inside another div element because the code works when I take it out of the rest of my program.我认为问题可能是 div 元素在另一个 div 元素内,因为当我将它从我的程序的 rest 中取出时代码有效。 Please teach me the path to redemtion.请教我救赎之道。

It looks like your code is correct.看起来你的代码是正确的。 One thing you can try is to make sure that the script is being executed after the elements are added to the page.您可以尝试的一件事是确保在将元素添加到页面后执行脚本。 You can do this by placing your script at the end of the <body> element, just before the closing </body> tag.为此,您可以将脚本放在<body>元素的末尾,就在结束</body>标记之前。

Here's an example:这是一个例子:

<body>
    ...
    <div class="gameBox">
        ...
    </div>
    <script>
        let elementsArray = document.querySelectorAll(".box");

        elementsArray.forEach(function(div) {
            div.addEventListener("click", function() {
                alert("AA");
            });
        });
    </script>
</body>

This ensures that the elements with the box class are added to the page before your script runs.这可确保在脚本运行之前将带有box class 的元素添加到页面中。

Another thing you can try is to add a debug statement to your code to see if the elementsArray variable is actually getting populated with the elements you expect.您可以尝试的另一件事是向您的代码添加调试语句,以查看elementsArray变量是否实际填充了您期望的元素。 You can do this by adding a console.log statement, like this:您可以通过添加console.log语句来执行此操作,如下所示:

let elementsArray = document.querySelectorAll(".box");

console.log(elementsArray);

elementsArray.forEach(function(div) {
    div.addEventListener("click", function() {
        alert("AA");
    });
});

This will print the elementsArray variable to the JavaScript console, which you can access in your web browser.这会将elementsArray变量打印到 JavaScript 控制台,您可以在 web 浏览器中访问它。 This will allow you to verify that the elementsArray variable contains the elements you expect.这将允许您验证elementsArray变量是否包含您期望的元素。

One solution is to add an event listener to the window object instead, and check if the clicked element is one of these .box elements.一种解决方案是改为向window object 添加事件侦听器,并检查单击的元素是否是这些.box元素之一。

window.addEventListener("click", (e) => {
  if (e.target.classList.contains("box")) {
    console.log(e.target.id);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将事件侦听器添加到从文件动态加载的SVG元素中? - How to Add Event Listeners to SVG Elements Loaded From File Dynamically? 如何在通过模板文字创建的元素中添加事件监听器? - How to add Event Listeners in elements created from Template Literals? 反应如何一次将事件侦听器添加到多个元素 - react how to add event listeners to multiple elements at once 如何将事件侦听器添加到彼此内部的元素 - How to add event listeners to elements that are inside one another 如何动态添加事件监听器 - How add event listeners dynamically 如何添加到 javascript 中的事件监听器 - How to add to event listeners in javascript 如何自动添加事件监听器? - How to add event listeners automatically? 如何将事件侦听器添加到动态创建的 HTML 列表元素? - How do I add event listeners to dynamically created HTML list elements? 如果不知道何时创建事件侦听器,如何将事件侦听器添加到HTML元素? - How do I add event listeners to HTML elements if I do not know when they will be created? 如何将事件侦听器添加到具有相同 class 的多个元素,然后仅为特定的其他元素更改 CSS - How to add event listeners to multiple elements with the same class and then only change CSS for specific other element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM