简体   繁体   English

如何在单击时在具有相同类名的多个元素上切换类

[英]How to toggle class on multiple elements with same class name on click



I can not get this code to work. 我无法使此代码正常工作。
I am trying to create a function that can listen to click on multiple elements with same class name, and then after click, toggle a specific class name on the next element with a specific class name. 我正在尝试创建一个函数,该函数可以侦听单击具有相同类名的多个元素,然后单击后,在具有特定类名的下一个元素上切换特定的类名。

I am trying to use a loop that loops through all the "buttons" (class="click-to-expand") and when you click a specific button, it should loop through the specific divs and toggle a class name on the next element with (class="expand"). 我正在尝试使用循环遍历所有“按钮”(class =“ click-to-expand”)的循环,当您单击特定按钮时,它应循环遍历特定的div并在下一个元素上切换类名称与(class =“ expand”)。

Any help would be very appreciated! 任何帮助将不胜感激!

 var expandArray = document.querySelectorAll('.expand'); document.querySelectorAll('.click-to-expand').forEach(function(i) { i.addEventListener('click', function(e) { e.target.expandArray[0].classList.toggle("hidden"); }) }); 
 .hidden {display: none} 
 <div> <div> <div class="click-to-expand">+</div> </div> </div> <div class="expand hidden">asd</div> <br> <div> <div> <div class="click-to-expand">+</div> </div> </div> <div class="expand hidden">asd</div> <br> <div> <div> <div class="click-to-expand">+</div> </div> </div> <div class="expand hidden">asd</div> 

You can try this 你可以试试这个


var expandArray = document.querySelectorAll('.expand');
var buttonArray = document.querySelectorAll('.click-to-expand');

document.querySelectorAll('.click-to-expand').forEach(function(i) {
  i.addEventListener('click', function(e) {
    const clickedBtnIndex = [...buttonArray].indexOf(e.target);
    expandArray[clickedBtnIndex].classList.toggle("hidden");
  })
});

The logic is to find out the index of the button which was clicked and use the same index to find the element in expandArray for which"hidden" should be toggled. 逻辑是找出被单击的按钮的索引,并使用相同的索引在expandArray中找到应为其切换“隐藏”的元素。

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

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