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

时间:2020-06-28 09:19:28

标签: javascript html css

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表单按钮”吗?

1 个答案:

答案 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;
}