我有一些按钮,我需要在单击时将一个按钮变为红色,将旧的红色按钮变为灰色,我该怎么做?



Html:

<div class="buttons">
<form>
<button class="all active" type="button">All</button>
<button class="print-temp" type="button">Print template</button>
<button class="web-temp" type="button">Web template</button>
<button class="user-inter" type="button">user interface</button>
<button class="mock-up" type="button">mock-up</button>
</form>
</div>

Js:

let buttons = document.querySelectorAll(".buttons form button");
for(let button of buttons) {
console.log(button);
button.onclick = function() {
buttons.classList.remove("active") //making old active button not active
button.classList.add("active") //making new active button
};
console.log(button);
}

每次我点击任何按钮时,我都会得到这个:

Uncaught TypeError: Cannot read property 'remove' of undefined
at HTMLButtonElement.button.onclick (main.js:8)

怎么了?是".按钮表单按钮"吗?

检查是否有任何按钮具有active类。如果是这样,则使用remove删除类。

这里也buttonsbuttons.classList.remove("active")指的是集合而不是单个元素

let buttons = document.querySelectorAll(".buttons form button");
for (let button of buttons) {
button.onclick = function() {
const getActiveBtn = document.querySelector('button.active');
if (getActiveBtn) {
getActiveBtn.classList.remove("active")
}
button.classList.add("active")

};
}
.active {
background: red;
color:#fff;
}
<div class="buttons">
<form>
<button class="all active" type="button">All</button>
<button class="print-temp" type="button">Print template</button>
<button class="web-temp" type="button">Web template</button>
<button class="user-inter" type="button">user interface</button>
<button class="mock-up" type="button">mock-up</button>
</form>
</div>

最新更新