2 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
嘗試使用我建議的 ID 來簡(jiǎn)化代碼!如此簡(jiǎn)單的任務(wù)太多了
'use strict'
const mainBtn = document.querySelectorAll('.main__btn');
const uomo = document.getElementById('uomo');
const donna = document.getElementById('donna');
mainBtn.forEach(el => {
el.addEventListener('click', (event) => {
const target = event.currentTarget;
console.log(target.id);
if(target.id=="uomo") {
donna.classList.remove('active');
uomo.classList.add('active');
} else {
donna.classList.add('active');
uomo.classList.remove('active');
}
});
});

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
const buttonOne = document.getElementById('buttonOne');
const buttonTwo = document.getElementById('buttonTwo');
buttonOne.addEventListener('click', makeActive);
buttonTwo.addEventListener('click', makeActive);
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>
你也可以這樣做。
添加回答
舉報(bào)