enter image description here我想访问链接到我的图标的data-id,以便使用它们来操作与这些id相关的部分
但问题是,当我按下图标时,有时会出现未定义的情况,有时会工作,我不知道为什么
请给我解释一下我做错了什么。
<body class="main-content">
<header class="section sec1 header active" id="home"></header>
<main>
<section class="section sec2 about" id="about"></section>
<section class="section sec3 portfolio" id="portfolio"></section>
<section class="section sec4 contact" id="contact"></section>
</main>
<div class="controls">
<div class="control control-1 active-btn" data-id="home">
<i class="fa-solid fa-house"></i>
</div>
<div class="control control-2" data-id="about">
<i class="fa-solid fa-user"></i>
</div>
<div class="control control-3" data-id="portfolio">
<i class="fa-solid fa-briefcase"></i>
</div>
<div class="control control-4" data-id="contact">
<i class="fa-solid fa-address-book"></i>
</div>
</div>
</body>
</html>
这是JavaScript
let active = document.querySelectorAll(".control");
let allsections = document.querySelectorAll(".main-content");
let section = document.querySelectorAll(".section");
function makingActive() {
active.forEach((e) => {
e.addEventListener("click", () => {
let active_1 = document.querySelectorAll(".active-btn");
active_1.forEach((e) => {
e.classList.remove("active-btn");
});
e.classList.add("active-btn");
});
});
allsections.forEach((e) => {
e.addEventListener("click", (e) => {
const id = e.target.dataset.id;
console.log(id);
section.forEach((sec) => {
sec.classList.remove("active");
});
const secActive = document.getElementById(id);
secActive.classList.add("active");
});
});
}
makingActive();
1条答案
按热度按时间iszxjhcz1#
我觉得你想要这样的东西: