javascript - 我有一些按钮,我需要在点击时将一个红色变为红色,而旧的红色按钮变为灰色,我该怎么做?
问题描述
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 表单按钮”吗?
解决方案
检查是否有任何按钮有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>
推荐阅读
- node.js - 如何在猫鼬中搜索几乎准确的所有值
- c# - 在 ASP.NET MVC 中使用上下文编辑 ASP.NET 用户后更新数据库
- mongodb - MongoDB 集群分片,没有主,只有一个辅助活动
- phaser-framework - 交互区域远小于实心圆的可见区域
- javascript - 如何检查 Javascript/jQuery 中的空 div?
- javascript - Javascript数字类型转换
- css - 将调色板转换为另一种颜色
- spring-security - 如何在 Spring Security thymeleaf sec 中使用列表:授权标签
- delphi - 如何添加新的ntfs文件夹权限
- c# - 如何检查日期是否在另一个日期的一周或一个月内