Как убрать активный класс с элемента при клике, если он уже имеет этот класс?

229
13 февраля 2017, 16:41

Не получается найти ошибку, почему класс не убирается при клике на элемент который уже имеет этот класс html:

       <div class="panel">
            <div class="panel-heading"><h4>panel 1</h4></div>
            <div class="panel-collapse">
                <div class="panel-body">
                    <p>1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch..</p>
                </div>
            </div>
        </div>
        <div class="panel">
            <div class="panel-heading"><h4>panel 2</h4></div>
            <div class="panel-collapse">
                <div class="panel-body">
                    <p>2 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.</p>
                </div>
            </div>
        </div>

js:

function ready() {
    var panels = document.getElementsByClassName("panel");
    var i;
    for (i = 0; panels.length > i; i++) {
        panels[i].onclick = function() {
            for (i = 0; panels.length > i; i++) {
                panels[i].classList.remove("active");
            }
            if (this.classList.contains("active")) {
                this.classList.remove("active")
            } else {
                this.classList.add("active")
            }
        };
    }
}
document.addEventListener("DOMContentLoaded", ready);
Answer 1

Можно обойтись и без циклов внутри обработчика.

Функция getElementsByClassName возвращает живую коллекцию. Таким образом получив один раз коллекцию для класса active

var actives = document.getElementsByClassName('active');

В ней всегда будут актуальные данные. И так как подразумевается только один активный элемент он будет доступен по индексу 0.

Теперь в обработчике достаточно проверить, что был предыдущий активный элемент и убрать с него класс active

var currentActive = actives[0];
if (currentActive)
  currentActive.classList.remove("active");

И если щелкнули не по активному элементу - нужно добавить этому элементу класс active

if (currentActive !== this)
  this.classList.add("active");

Пример в сборе:

var panels = document.getElementsByClassName("panel"); 
var actives = document.getElementsByClassName('active'); 
for (i = 0; panels.length > i; i++) { 
  panels[i].onclick = function() { 
    var currentActive = actives[0]; 
    if (currentActive) 
      currentActive.classList.remove("active"); 
 
    if (currentActive !== this) 
      this.classList.add("active"); 
  }; 
}
.active { 
  border: solid 2px green; 
}
<div class="panel"> 
  <div class="panel-heading"> 
    <h4>panel 1</h4> 
  </div> 
  <div class="panel-collapse"> 
    <div class="panel-body"> 
      <p>1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch..</p> 
    </div> 
  </div> 
</div> 
<div class="panel"> 
  <div class="panel-heading"> 
    <h4>panel 2</h4> 
  </div> 
  <div class="panel-collapse"> 
    <div class="panel-body"> 
      <p>2 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.</p> 
    </div> 
  </div> 
</div>

Answer 2

в цикле пропускать элемент, на который щелкнули

т.e.

for (i = 0; panels.length > i; i++) {
  if (panels[i] != this)
    panels[i].classList.remove("active");
}
READ ALSO
по нажатию одной кнопки нажимались и другие

по нажатию одной кнопки нажимались и другие

Всем приветНачал изучать html/css

396
Rails запит javacript помилка [требует правки]

Rails запит javacript помилка [требует правки]

Добрый день у меня есть проблема и она сводит меня с умакод

236
Не понимаю, в чем проблема?

Не понимаю, в чем проблема?

Есть задача: нужно вызвать функцию sumTo с аргументом nn - это сколько раз нужно добавить к i единицу

216