简体   繁体   中英

Why can I only fire this function once?

I have this function:

const sliderTextChange = document.getElementsByClassName('slider') // text change

const changeSliderText = change => {
  const sliderLeft = document.getElementsByClassName('switch-left')
  const sliderRight = document.getElementsByClassName('switch-right')

  for (let i = 0; i < change.length; i++) {
    change[i].addEventListener('click', () => {
      sliderRight[i].style.display = 'flex';
      sliderLeft[i].style.display = 'none';
    });
  }
}

changeSliderText(sliderTextChange);

This is one of the many sliders on the website:

<div class="flex-column">
  <h3>Text Colour</h3>
  <div class="slider">
    <div class="slider-back"></div>
    <div class="slider-circle"></div>
  </div>
  <h3 class="switch-left">White</h3>
  <h3 class="switch-right">Black</h3>
</div>

This function is quite a lot like many other functions in my code but they're only firing once. AKA I fire the event listener and but then I can't fire it again.

What's the issue here?

I have tried to simplify your code and keep the scope to be modular and reusable view.

 function bindEvent() { const sliderList = document.querySelectorAll('.slider'); [...sliderList].forEach((slider) => slider.addEventListener('click', () => { const left = slider.parentElement.querySelector('.switch-left'); const right = slider.parentElement.querySelector('.switch-right'); const leftDisplay = left.style.display || 'flex'; const rightDisplay = right.style.display || 'none'; left.style.display = rightDisplay; right.style.display = leftDisplay; }, false)); } window.onload = bindEvent; 
 <div> <button class="slider"> - SLIDER 1 - </button> <div class="switch-left">L</div><div class="switch-right">R</div> </div> <div> <button class="slider"> - SLIDER 2 - </button> <div class="switch-left">L</div><div class="switch-right">R</div> </div> <div> <button class="slider"> - SLIDER 3 - </button> <div class="switch-left">L</div><div class="switch-right">R</div> </div> <div> <button class="slider"> - SLIDER 4 - </button> <div class="switch-left">L</div><div class="switch-right">R</div> </div> 

Parameters you have chosen for your function are not really intuitive and make your example more complex.

We use querySelector , it's nicer to read but if you prefer speed, just go for getElementsByClassName , it also works on any DOM element.

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