简体   繁体   English

删除所有活动的班级,然后切换班级-javascript

[英]Remove all class active then toggle class - javascript

I'm trying to create a simple accordion, I've got the javascript working to toggle the class active on click of the item, but on the HTML i've already got the first item as active. 我正在尝试创建一个简单的手风琴,我已经使用JavaScript来在单击该项目时将类切换为活动状态,但是在HTML上我已经将第一个项目设置为活动状态。

So basically I want it to work where you click other accordion header, the one that is open closes, and the one you clicked on opens. 因此,基本上,我希望它可以在您单击其他手风琴标题的情况下工作,打开的一个关闭,然后单击的一个打开。

I tried using classList.remove(active) before the toggle but threw and error. 我尝试在切换之前使用classList.remove(active),但抛出并出错。

Here is the link to what i've done so far: 这是我到目前为止所做的链接:

var accordionLink = document.getElementsByClassName('accordion-item')
    for(var i = 0; i < accordionLink.length; i++) {
        var elem = accordionLink[i];
        elem.addEventListener('click', function(event){
            this.classList.toggle('active');
            event.preventDefault();
        }, false);
    }

https://codepen.io/anishpixellabs/pen/deNbKE https://codepen.io/anishpixellabs/pen/deNbKE

Any help would be great. 任何帮助都会很棒。

Regards 问候

Have a look at this lines, I'm pretty sure something like this should work. 看看这行,我很确定这样的东西应该可以工作。

 var accordionLink = document.getElementsByClassName('accordion-item') for (var i = 0; i < accordionLink.length; i++) { var elem = accordionLink[i]; elem.addEventListener('click', function(event) { for (var j = 0; j < accordionLink.length; j++) accordionLink[j].classList.remove("active") this.classList.add('active'); event.preventDefault(); }, false); } 

Some explanations: 一些解释:

for (var i = 0; i < accordionLink.length; i++) {     // loop trough all elements to add "onClick event"
  var elem = accordionLink[i];                       // "elem" is current element
  elem.addEventListener('click', function(event) {   // adding "onClick" to current "elem"
    for (var j = 0; j < accordionLink.length; j++)   // ONCLICK trigger: "Loop trough all elements of 'accordionLink'
      accordionLink[j].classList.remove("active")    // remove the 'active class' for every occurrence of 'accordionLink'-class"
    this.classList.add('active');                    // add "active"-class to element that received ONCLICK-trigger
    event.preventDefault();
  }, false);
}

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

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