我试图通过在单击时添加一个“活动”类来突出显示某个div,并从所有其他单击过并具有活动类的div中删除“活动”类。
一次只有一个div可以有活动的班级
let i = 0;
for (; i < list_wrapper.children.length; i++) {
console.log(list_wrapper.children[i]);
list_wrapper.children[i].addEventListener('click', function () {
if (this.className.indexOf('active') === -1) {
this.classList.add('active');
}
if (this.className.indexOf('active') > -1) {
// this.classList.remove('active');
console.log(list_wrapper.children)
}
})
}
答案 0 :(得分:1)
document.querySelectorAll('#wrapper li').forEach(function (el) {
el.addEventListener('click', function (e) {
document.querySelectorAll('#wrapper li').forEach(x => x.classList.remove('active'));
e.currentTarget.classList.toggle('active');
});
});
.active {
color: red
}
<ul id="wrapper">
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
答案 1 :(得分:0)
您可以执行this.classList.remove('active');
而不检查所有元素是否存在,然后将其添加到单击的元素中:
const divs = document.querySelectorAll('div');
divs.forEach(e => {
e.addEventListener('click', (e) => {
// remove the class from the others
divs.forEach(d => d.classList.remove('active'));
// add the class to the current one
e.target.classList.add('active');
});
})
div{
padding: 10px;
float: left;
margin: 10px;
cursor: pointer;
}
.active{
background: red;
}
<div>
hello
</div>
<div>
lorem
</div>
<div>
world
</div>