javascript标签无法正常工作

时间:2016-11-16 15:30:08

标签: javascript tabs babel

我有一个问题。一切正常,但如果我添加更多标签,那么" isVisible" class被添加到所有其他选项卡。我该如何解决这个问题?

HTML:

<div class="content">
  <button class="nextTab">Next Tab</button>
  <div class="tabs">
    <div class="tabs__item isActive">
      <p>1 Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
    </div>
    <div class="tabs__item">
      <p>2 Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
    </div>
  </div>
</div>

Javascript(Babel)

(() => {
    const tabs = document.querySelector('.tabs')
        , tabsItem = document.querySelectorAll('.tabs__item')
        , nextTab = document.querySelector('.nextTab')

    nextTab.addEventListener('click', () => {
        for(let i = 0; i < tabsItem.length; i++) {
            tabsItem[i].classList.toggle('isActive')
        }
    })
})()

1 个答案:

答案 0 :(得分:0)

您应该跟踪当前的标签索引,以便能够切换到下一个。

(() => {
    const tabs = document.querySelector('.tabs')
        , tabsItem = document.querySelectorAll('.tabs__item')
        , nextTab = document.querySelector('.nextTab')
        , currentTab = 0;

    nextTab.addEventListener('click', () => {
      if (++currentTab > tabsItem.length - 1) currentTab = 0; 
      document.querySelector('.isActive').classList.remove('isActive'));
      tabsItem[currentTab].classList.add('isActive'))
    });
})()