如何将事件侦听器添加到数组中的所有项目

How to add an event listener to all items in array

所以这是菜鸟..但我正在尝试通过更多的尽职调查来完成挑战,而不仅仅是下载答案,

我当前的 html 代码是:

<!DOCTYPE html>
<html lang="en" dir="ltr">

    <head>
      <meta charset="utf-8">
      <title>Drum Kit</title>
      <link rel="stylesheet" href="styles.css">
      <link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
    </head>
    
    <body>
    
      <h1 id="title">Drum  Kit</h1>
      <div class="set">
        <button class="w drum">w</button>
        <button class="a drum">a</button>
        <button class="s drum">s</button>
        <button class="d drum">d</button>
        <button class="j drum">j</button>
        <button class="k drum">k</button>
        <button class="l drum">l</button>
      </div>
    
    
      <footer>
        Made with ❤️ in London.
      </footer>
      <script src="index.js" charset="utf-8"></script>
    </body>

我的 javascript 代码:

   document.querySelector("button").addEventListener("click", handleClick);
    function handleClick() {
        alert("I got clicked!");
    }
    
    
    document.querySelectorAll(".drum")[1, 2, 3, 4, 5, 6].addEventListener("click", handleClick);

本质上,当前代码是运行事件监听器 仅针对数组的第一项和最后一项,尝试将其添加到所有 6 但卡住了

感谢大家

document.querySelectorAll(".drum").forEach(el => el.addEventListener("click", handleClick));

您需要 forEach 到 运行 一些关于 所有 元素的代码。

不是将侦听器附加到每个按钮,而是将 一个 添加到容器 (set) 并使用 event delegation,让该侦听器捕获所有从其子元素“冒出”DOM 并调用函数的事件。

const set = document.querySelector('.set');
set.addEventListener('click', handleClick, false);

function handleClick(e) {  
  if (e.target.matches('button')) {
    const { textContent } = e.target;
    console.log(`Banging the ${textContent} drum!`);
  }
}
<h1 id="title">Drum  Kit</h1>
<div class="set">
  <button class="w drum">w</button>
  <button class="a drum">a</button>
  <button class="s drum">s</button>
  <button class="d drum">d</button>
  <button class="j drum">j</button>
  <button class="k drum">k</button>
  <button class="l drum">l</button>
</div>
<footer>
  Made with ❤️ in London.
</footer>

其他文档