在JavaScript中-选择所有具有相同类的元素-单击除外

目前,我得到的结果很好,但是正在检查一种智能简单的解决方案

使用jquery not有类似的答案



let color = document.querySelectorAll('.color');

let length = color.length;

// for (let i = 0; i < length; i++) {
//     color[i].onclick = () => {
//         color[i].classList.toggle('gold');
//     }
// }



// if gold exists on clicked element then remove it
// if gold not exists on clicked element then remove from all element and add only on clicked element
for (let i = 0; i < length; i++) {
    color[i].onclick = () => {
        if (color[i].classList.contains('gold')) {
            color[i].classList.toggle('gold');  // remove / toggle
        } else {
            for (let x = 0; x < length; x++) {
                color[x].classList.remove('gold');
            }
            color[i].classList.toggle('gold');  // add / toggle
        }
    }
}

.main {
    display: flex;
    justify-content: center;
}
.color {
    margin: 5px;
    width: 100px;
    height: 100px;
    border: 1px solid #ddd;
}

.gold {
    background-color: gold;
}

<div class="main">
    <div class="color"></div>
    <div class="color"></div>
    <div class="color"></div>
    <div class="color"></div>
    <div class="color"></div>
</div>





demo

最佳答案

let color = document.querySelectorAll('.color')
let gold = 'gold'

color.forEach(
  (c) => c.onclick = (e) => {
      color.forEach(
        (c) => c.classList[e.target==c?'toggle':'remove'](gold)
      )
    }
)

.main {
    display: flex;
    justify-content: center;
}
.color {
    margin: 5px;
    width: 100px;
    height: 100px;
    border: 1px solid #ddd;
}

.gold {
    background-color: gold;
}

<div class="main">
    <div class="color"></div>
    <div class="color"></div>
    <div class="color"></div>
    <div class="color"></div>
    <div class="color"></div>
</div>

09-19 09:33