如何将 EventListener 应用于数组的每个元素?

How to apply EventListener to each element of an array?

我正在尝试对数组中的每个元素应用 onclick 事件监听器。我怎样才能做到这一点?我尝试使用 querySelectorAll 但它不起作用。您可以在此处查看代码:https://codesandbox.io/s/unruffled-ishizaka-4g9uq?file=/src/App.js:93-229。在此先感谢您的帮助。

let head = document.querySelectorAll("heading");
    for (let i of head)
      i.addEventListener("click", function h() {
        let a = document.getElementById("subheading");
        a.style.display = "none";
      }); 

Link 到 CodeSandBox

错误:

  1. 您可能需要为元素提供 class 名称 headings,因为 HTML 文档只有一个唯一 ID。
  2. useEffect 中遍历元素时,您需要像这样找到 const a = i.querySelector(".subheading")

Link 到 CodeSandBox

import "./styles.css";
import { useEffect } from "react";

export default function App() {
  const headings = ["1. Heading", "2. Heading", "3. Heading"];
  const subheadings = ["1. Subheading", "2. Subheading", "3. Subheading"];

  useEffect(() => {
    const head = document.querySelectorAll(".heading");

    head.forEach((i) => {
      i.addEventListener("click", function () {
        const a = i.querySelector(".subheading");
        a.style.display = "none";
      });
    });
  }, []);

  return (
    <div className="App">
      <div>
        {headings.map((val, index) => (
          <li key={index} style={{ listStyle: "none" }} className="heading">
            <a href="#">{val}</a>
            <ul className="subheading">
              {subheadings.map((val, index2) => (
                <li key={index2} style={{ listStyle: "none" }}>
                  <a href="#">{val}</a>
                </li>
              ))}
            </ul>
          </li>
        ))}
      </div>
    </div>
  );
}

Link 到 CodeSandBox