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)
怎么了?是“ .buttons表单按钮”吗?
答案 0 :(得分:2)
检查是否有任何按钮具有active
类。如果是这样,请使用remove
删除该类。
这里buttons
的{{1}}也是指集合,而不是单个元素
buttons.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;
}