删除所有活动类然后切换类 - javascript

时间:2018-04-28 10:28:39

标签: javascript events addeventlistener

我试图创建一个简单的手风琴,我已经让javascript工作在点击该项目时激活课程,但在HTML上我已经获得了第一个项目活性

所以基本上我希望它能够在你点击其他手风琴标题的地方工作,打开的那个会关闭,你点击的那个会打开。

我尝试在切换之前使用classList.remove(active)但是抛出了错误。

以下是我到目前为止所做的工作的链接:

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

任何帮助都会很棒。

此致

1 个答案:

答案 0 :(得分:0)

看看这一行,我很确定这样的事情应该有用。

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);
}

一些解释:

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);
}