首页 > 解决方案 > 我有一些按钮,我需要在点击时将一个红色变为红色,而旧的红色按钮变为灰色,我该怎么做?

问题描述

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

标签: javascripthtmlcss

解决方案


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

buttons这里也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;
}
<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>


推荐阅读