简体   繁体   中英

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.
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.
In HTML I have 4 divs that share the same class and it looks like that:

<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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM