[英]classList.add works but toggle doesn't
My HTML 我的HTML
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<button id="button">button</button>
My js 我的js
var button = document.querySelector('#button');
var chapter = document.querySelectorAll('.chapter');
for(var i = 0; i < chapter.length; i++){
button.addEventListener('click', function(){
for(var i = 0; i < chapter.length; i++) {
chapter[i].classList.add('active');
}
});
}
This adds the class of "active" on clicking the button. 单击按钮将添加“活动”类。
But toggle doesn't work. 但是切换不起作用。 Instead of
代替
chapter[i].classList.add('active');
When I do, 当我做,
chapter[i].classList.toggle('active');
the class of "active" does not toggle. “活动”类别不会切换。 console shows no error.
控制台未显示任何错误。
So I tried to check the class of "active" first & remove the class if the class exists. 因此,我尝试首先检查“活动”的类并删除该类(如果该类存在)。 I know I was trying to reinvent the toggle function;
我知道我正在尝试重新发明切换功能。 as stated above, toggle wasn't working so I tried it anyway.
如上所述,切换功能无效,因此我还是尝试了一下。
if (chapter[i].contains('active')){
chapter[i].classList.remove('active');
And I got a slew of error messages. 而且我收到了很多错误消息。 This is as far as I got.
据我所知。 I somehow felt that this wasn't going to work but just tried it anyway.
我不知何故感觉这是行不通的,但还是尝试了一下。
I am stumped. 我感到难过。
Can anyone point out why classList.toggle isn't working in my code & how this can be fixed? 谁能指出为什么classList.toggle在我的代码中不起作用以及如何解决?
Thanks. 谢谢。
You have one too many loop. 您有一个太多的循环。 Remove the outer one:
卸下外面的一个:
var button = document.querySelector('#button'); var chapter = document.querySelectorAll('.chapter'); button.addEventListener('click', function(){ for(var i = 0; i < chapter.length; i++) { chapter[i].classList.toggle('active'); } });
.active{ color: red; }
<div class="chapter">text text text </div> <div class="chapter">text text text </div> <div class="chapter">text text text </div> <div class="chapter">text text text </div> <button id="button">button</button>
var button = document.querySelector('#button'); var chapters = document.querySelectorAll('.chapter'); button.addEventListener('click', function(){ for(var index = 0; index < chapters.length; index++) { if(chapters[index].classList.contains('active')){ chapters[index].classList.remove('active'); }else{ chapters[index].classList.add('active'); } } });
.active { color: red; }
<div class="chapter">text text text </div> <div class="chapter">text text text </div> <button id="button">Toggle Color</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.