[英]“classList.add” doesn't add a class to a div and a form elements
[英]classList.add works but toggle doesn't
我的HTML
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<button id="button">button</button>
我的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');
}
});
}
单击按钮将添加“活动”类。
但是切换不起作用。 代替
chapter[i].classList.add('active');
当我做,
chapter[i].classList.toggle('active');
“活动”类别不会切换。 控制台未显示任何错误。
因此,我尝试首先检查“活动”的类并删除该类(如果该类存在)。 我知道我正在尝试重新发明切换功能。 如上所述,切换功能无效,因此我还是尝试了一下。
if (chapter[i].contains('active')){
chapter[i].classList.remove('active');
而且我收到了很多错误消息。 据我所知。 我不知何故感觉这是行不通的,但还是尝试了一下。
我感到难过。
谁能指出为什么classList.toggle在我的代码中不起作用以及如何解决?
谢谢。
您有一个太多的循环。 卸下外面的一个:
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.