简体   繁体   English

Javascript addEventListener 仅将 class 添加到一个元素

[英]Javascript addEventListener only add a class to one element

I am trying to create a tab-like system where when you click a tab, it removes the classes from other tabs and adds them to the clicked class我正在尝试创建一个类似选项卡的系统,当您单击选项卡时,它会从其他选项卡中删除类并将它们添加到单击的 class

heres the code这是代码

JS: JS:

const tabs = document.getElementsByClassName('Tab');

for (let tab=0; tab < tabs.length; tab++){
  tabs[tab].addEventListener('click', (e)=>{
    for (let tab=0; tab < tabs.length; tab++){
      e.target.classList.remove('active-tab')
    }
    e.target.classList.add('active-tab')
  })
}

css: css:

.active-tab {
  border-bottom: 10px solid pink;
}

It is actually adding the class and adding a pink underline, but it doesn't remove the other classes, so all the tabs can have the underline它实际上是添加 class 并添加粉红色下划线,但它不会删除其他类,因此所有选项卡都可以有下划线

Example:例子:

The Error错误

It looks like the reason it is not removing any of the classes is because you are using e.target.classList.remove('active-tab') which removes the class from the element/tab that was clicked.看起来它没有删除任何类的原因是因为您正在使用e.target.classList.remove('active-tab')从单击的元素/选项卡中删除 class 。 You are looping through the elements/tabs, but not actually selecting any of them.您正在遍历元素/选项卡,但实际上并未选择其中任何一个。

So you would want to use something like tabs[tab].classList.remove('active-tab') instead.因此,您可能想使用tabs[tab].classList.remove('active-tab')之类的东西。

const tabs = document.getElementsByClassName('Tab');

for (let tab=0; tab < tabs.length; tab++){
  tabs[tab].addEventListener('click', (e)=>{
    for (let tab=0; tab < tabs.length; tab++){
      tabs[tab].classList.remove('active-tab')
    }
    e.target.classList.add('active-tab')
  })
}

For the sake of avoiding for loops with list of elements/arrays, here is alternative way to do this same thing为了避免带有元素/数组列表的for循环,这里有另一种方法来做同样的事情

document.querySelectorAll('.Tab').forEach(el => {
    el.addEventListener("click", e => {
        document.querySelectorAll("active-tab").forEach(t => {
            t.classList.remove("active-tab");
        });
        e.target.classList.add("active-tab");
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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