javascript - 按钮样式错误
问题描述
我想使用按钮从我的用户那里接收信息,所以我为此创建了两个部分。当用户单击一个按钮时,我需要它来更改其样式,以便用户即使单击另一部分中的另一个按钮也会看到他们单击的内容有所不同。问题是,当单击另一个按钮时,另一个部分会失去其样式(因此用户不会知道他之前单击了什么)。我粘贴了有问题的部分的html代码(下)
<div>
<p><strong>Network</strong></p>
<button class="btn25" onclick = "gfg_Run()">
MTN
</button>
<button class="btn25">
Glo
</button>
<button class="btn25">
9 Mobile
</button>
<button class="btn25">
Airtel
</button>
</div>
<div>
<p><strong>Data</strong></p>
<button class="btn25">
1Gb
</button>
<button class="btn25">
2Gb
</button>
<button class="btn25">
3Gb
</button>
<button class="btn25">
5Gb
</button>
<button class="btn25">
10Gb
</button>
</div>
解决方案
我需要它来改变它的风格,这样用户就会看到不同
创建一个class
被调用active
,然后设置按钮以在用户选择它们时使用该类。
问题是,当单击另一个按钮时,另一个部分会失去其样式
问题是您需要将每个组分开。我在区分两组class
的父级上添加了一个:“数据”或“速度”。div
每个组的按钮背景将变为蓝色,因为它仅限于查询中的该类,如“.data”在此处所做的那样:
document.querySelectorAll('.data .btn25');
这是一个显示基本技术的示例片段。
const dataChoices = document.querySelectorAll('.data .btn25');
dataChoices.forEach(function(choice) {
choice.addEventListener('click', function() {
removeClass(dataChoices);
this.classList.add('active');
});
});
const speedChoices = document.querySelectorAll('.speed .btn25');
speedChoices.forEach(function(choice) {
choice.addEventListener('click', function() {
removeClass(speedChoices);
this.classList.add('active');
});
});
function removeClass(dataGroup) {
dataGroup.forEach(function(choice) {
choice.classList.remove('active');
});
}
.active {
background-color: lightblue;
}
div {
float: left;
margin-right: 10px;
}
<div class="data">
<p><strong>Data</strong></p>
<button id="1" class="btn25">1Gb</button>
<button id="2" class="btn25">2Gb</button>
<button id="3" class="btn25">3Gb</button>
<button id="4" class="btn25">5Gb</button>
<button id="5" class="btn25">10Gb</button>
</div>
<div class="speed">
<p><strong>Speed</strong></p>
<button id="1" class="btn25">1Mbps</button>
<button id="2" class="btn25">2Mbps</button>
<button id="3" class="btn25">3Mbps</button>
<button id="4" class="btn25">5Mbps</button>
<button id="5" class="btn25">10Mbps</button>
</div>
推荐阅读
- r - 如何通过匹配字母和字符来提取文本?
- python-3.x - 在 gensim 中加载 pickle 文件
- python - 在 sympy 表达式中使用矩阵乘法运算符
- flutter - 颤动文本按钮填充问题
- dotnetnuke - 如何向 Dnn 添加新的用户配置文件字段?
- c# - EF Core 6 JSON 列示例
- python - 限制员工发布工作的记录规则,odoo 14
- amazon-s3 - 通过 AWS-PHP-SDK 上传 S3 文件的访问被拒绝
- python - PyQt5出错时弹出qmessage而不是闪退
- snowflake-cloud-data-platform - 为什么即使仓库冷启动,使用的平均缓存也很高?