猿问

JS 上只有一个活动按钮

需要做到这一点,以便您只能从两个按钮中选择一个活动按钮。HTML


<button class="main__btn">uomo</button>

<button class="main__btn">donna</button>

JS


'use strict'

const mainBtn = document.querySelectorAll('.main__btn');

mainBtn.forEach(el => {

    el.addEventListener('click', (event) => {

        const target = event.currentTarget;

        if(el.classList.contains('active')) {

            el.classList.remove('active');

        } else {

            el.classList.add('active');

        }

    });

});


拉莫斯之舞
浏览 135回答 2
2回答

四季花海

尝试使用我建议的 ID 来简化代码!如此简单的任务太多了&nbsp;'use strict'&nbsp; &nbsp; const mainBtn = document.querySelectorAll('.main__btn');&nbsp; &nbsp; const uomo = document.getElementById('uomo');&nbsp; &nbsp; const donna = document.getElementById('donna');&nbsp; &nbsp; mainBtn.forEach(el => {&nbsp; &nbsp; &nbsp; &nbsp; el.addEventListener('click', (event) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const target = event.currentTarget;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(target.id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(target.id=="uomo") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; donna.classList.remove('active');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uomo.classList.add('active');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; donna.classList.add('active');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uomo.classList.remove('active');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });

qq_花开花谢_0

const buttonOne = document.getElementById('buttonOne');const buttonTwo = document.getElementById('buttonTwo');buttonOne.addEventListener('click', makeActive);buttonTwo.addEventListener('click', makeActive);&nbsp;function makeActive(event){if(!event.target.classList.contains('active')){buttonOne.classList.toggle('active')buttonTwo.classList.toggle('active')}}.active{background-color:black;color:white;}<button id='buttonOne' class="main__btn active" >uomo</button><button id='buttonTwo' class="main__btn">donna</button>你也可以这样做。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答