![](/img/trans.png)
[英]How do I toggle a class on click of an element but remove the same class from all other elements using JQuery?
[英]Remove class from all elements and then toggle it on selected element
我正在嘗試從所有行中刪除一個類,並在所選行上切換它。 我正在嘗試用javascript實現。 我有一堆看起來像下面的行。 目前,我的結果不一致,有時其他行仍保持打開狀態。 我究竟做錯了什么?
<section class="table-body">
<section class="table-row u-flex">
<div class="table-category">
...
</div>
</section>
<section class="table-row u-flex">
<div class="table-category">
...
</div>
</section>
...
</section>
使用Javascript
function openMenu(e) {
for( let i = 0; i < e.closest('.table-body').children.length; i++ ) {
document.querySelector('.table-row').classList.remove('is-open');
}
// add the active class to the row you just clicked
if (e.closest('.table-row') !== null) {
e.closest('.table-row').classList.toggle('is-open');
}
}
如我所見,問題是,首先從每個.table-row
刪除該類,然后將其切換到觸發事件的那個。
這導致以下情況:
1.觸發器行具有"is-open"
:
"is-open"
類,然后使用toggle命令再次添加它。 2.觸發器行沒有“ is-open”類
我要做的是以下幾點:
function openMenu(e) {
const openRow = !e.closest('.table-row').classList.contains('is-open');
for( let i = 0; i < e.closest('.table-body').children.length; i++ ) {
document.querySelector('.table-row').classList.remove('is-open');
}
if (openRow) {
e.closest('.table-row').classList.add('is-open');
}
}
這應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.