[英]For each element inside an array I want it to have another for each that will have unique action
I wanted to make each element inside myArray will have it's unique action, but I end up with only one of them working.我想让 myArray 中的每个元素都有它独特的动作,但我最终只有一个在工作。
I have tried one more way of doing it that worked, but it was a complete boilerplate and I'm looking for a better solution than that.我已经尝试了另一种可行的方法,但它是一个完整的样板,我正在寻找比这更好的解决方案。
More details: For each element (Another array of buttons) inside myArray it will have unique action like scrollIntoView of some element in HTML.更多详细信息:对于 myArray 中的每个元素(另一个按钮数组),它将具有独特的操作,例如 HTML 中某些元素的 scrollIntoView。
In HTML I have 4 divs that share the same class and it looks like that:在 HTML 我有 4 个 div 共享相同的 class,它看起来像这样:
<div class='firstDiv'>
<button class="teamBtn"></button>
<button class="serviceBtn"></button>
etc..
</div>
<div class='secondDiv'>
<button class="teamBtn"></button>
<button class="serviceBtn"></button>
etc..
</div>
let aboutSection = document.querySelector('.about')
let serviceSection = document.querySelector('.services')
let teamSection = document.querySelector('.team')
let homeBtn = document.querySelectorAll('.homeBtn');
let aboutBtn = document.querySelectorAll('.aboutBtn');
let serviceBtn = document.querySelectorAll('.serviceBtn')
let teamBtn = document.querySelectorAll('.teamBtn')
let myArray = [];
myArray[0] = homeBtn;
myArray[1] = aboutBtn;
myArray[2] = serviceBtn;
myArray[3] = teamBtn;
myArray.forEach(el => {
addEventListener('click', () => {
teamBtn.forEach(() => {
teamSection.scrollIntoView();
});
serviceBtn.forEach(() => {
serviceSection.scrollIntoView();
});
})
})
You really want delegation from a container wrapping ALL divs.你真的想要一个包装所有 div 的容器的委托。 Then only one event handler is needed for all buttons
那么所有按钮只需要一个事件处理程序
document.getElementById("nav").addEventListener("click",function(e) { const tgt = e.target.closest("button") if (tgt && (tgt.classList.contains("teamBtn") ||tgt.classList.contains("serviceBtn"))) { document.getElementById(tgt.dataset.id).scrollIntoView(); } })
section div { height: 500px; background-color: red; border: 1px solid black; }
<nav id="nav"> <div class="firstDiv"> <button class="teamBtn" data-id="team1">Team 1</button> <button class="serviceBtn" data-id="service1">Service 1</button> </div> <div class="secondDiv"> <button class="teamBtn" data-id="team2">team 2</button> <button class="serviceBtn" data-id="service2">Service 2</button> </div> </nav> <section id="content1"> <div id="team1">Team 1</div> <div id="service1">Service 1</div> </section> <section id="content2"> <div id="team2">Team 2</div> <div id="service2">Service 2</div> </section>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.