html 我想简化这段JavaScript代码,有很多子元素

gkl3eglg  于 2023-04-18  发布在  Java
关注(0)|答案(1)|浏览(106)

我在做菜单,
单击第一项时,menu pic 1
点击第二项时,menu pic 2
我已经在样式表中为类'on'创建了样式。

colorItems = document.querySelector('#color').children[1]

colorItems.children[0].addEventListener('click', () => {
    colorItems.children[0].classList.toggle('on')
    colorItems.children[1].classList.remove('on')
    colorItems.children[2].classList.remove('on')
    colorItems.children[3].classList.remove('on')
})
colorItems.children[1].addEventListener('click', () => {
    colorItems.children[0].classList.remove('on')
    colorItems.children[1].classList.toggle('on')
    colorItems.children[2].classList.remove('on')
    colorItems.children[3].classList.remove('on')
})
colorItems.children[2].addEventListener('click', () => {
    colorItems.children[0].classList.remove('on')
    colorItems.children[1].classList.remove('on')
    colorItems.children[2].classList.toggle('on')
    colorItems.children[3].classList.remove('on')
})
colorItems.children[3].addEventListener('click', () => {
    colorItems.children[0].classList.remove('on')
    colorItems.children[1].classList.remove('on')
    colorItems.children[2].classList.remove('on')
    colorItems.children[3].classList.toggle('on')
})
lokaqttq

lokaqttq1#

基于你的代码,这里有一个解决方案:

#coloras i see its yourparentcontainer and its haschildrenlet assume they are buttons,you need to select the children usingquerySelectorAlland loop through them,whenever you click on abuttonyou should add**.oncss class toclicked buttonand remove this class from itssiblings**here is workable example:

let colorItems = document.querySelectorAll('#color button');

colorItems.forEach(item => {
    item.addEventListener('click', ()=> {
        colorItems.forEach(i => i != item ? i.classList.remove('on') : i.classList.add('on'));
    });
});
.on {
    background-color: yellow;
}
<div id="color">
    <button>red</button>
    <button>blue</button>
    <button>white</button>
    <button>black</button>
</div>

相关问题