【问题标题】:How to remove a class on all the other elements except on the element that was clicked如何删除所有其他元素上的类,除了被点击的元素
【发布时间】:2019-06-25 20:44:51
【问题描述】:

您好,我想删除除单击元素之外的所有其他元素的类。

到目前为止,我的代码看起来像这样,但我找不到解决方案

const elements = document.querySelectorAll(".element");

function toggleOpen() {
    this.classList.toggle('open');
    elemets.forEach(ele => {
        ele.classList.remove('open'); // buts this removes the class from all 
       the elements I am looking for something that removes the class on just 
       the other one element containing the class except on the clicked one.
    }) 
}

elements.forEach(ele => ele.addEventListener('click', toggleOpen));

【问题讨论】:

  • element.classList.add("open");每个之后
  • this.classList.add("open"); 在 forEach 循环之后。还有一个错字:elemets

标签: javascript events classname


【解决方案1】:

您真的很接近,只需在 forEach 循环中使用 if 子句通过与 this 比较来跳过您单击的元素,另外,您在函数中有错字:

const elements = document.querySelectorAll('.element');

function toggleOpen() {
    this.classList.toggle('open');
    elements.forEach(ele => {
        if (ele !== this) ele.classList.remove('open');
    });
}

elements.forEach(ele => ele.addEventListener('click', toggleOpen));
.element { color: red; }
.open { color: green; }
<button class="element">1</button>
<button class="element">2</button>
<button class="element">3</button>
<button class="element">4</button>

【讨论】:

  • 这是最好的答案,谢谢
  • 很高兴为您提供帮助! :)
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 2017-04-06
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多