![](/img/trans.png)
[英]How to apply an eventListener to multiple elements with the same class and have each element respond independently
[英]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";
});
链接到CodeSandBox
错误:
headings
,因为 HTML 文档只有一个唯一的 id。useEffect
元素时,您需要像这样找到const a = i.querySelector(".subheading")
。链接到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>
);
}
链接到CodeSandBox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.