html - 单选按钮不起作用 - 状态没有改变
问题描述
我正在使用一个教程,它教我如何制作自定义单选按钮。我的问题是,当我制作 3 个单选按钮时,只有第一个在工作。无法单击另外两个。当我单击另一个按钮时,只有第一个按钮起作用。
HTML:
<label for="myRadioId" class="radio">
<input type="radio" name="myRadioField" id="myRadioId" class="radio__input">
<div class="radio__radio"></div>
option 1
</label><br>
<label for="myRadioId" class="radio">
<input type="radio" name="myRadioField" id="myRadioId" class="radio__input">
<div class="radio__radio"></div>
option 2
</label><br>
<label for="myRadioId" class="radio">
<input type="radio" name="myRadioField" id="myRadioId" class="radio__input" disabled>
<div class="radio__radio"></div>
disabled
</label>
CSS:
.radio {
cursor: pointer;
display: inline-flex;
}
.radio__input {
display: none;
}
.radio__radio {
width: 1.25rem;
height: 1.25rem;
border: 2px solid #d8e4e2;
border-radius: 50%;
margin-right: 10px;
box-sizing: border-box;
padding: 2px;
}
.radio__radio::after {
content: "";
width: 100%;
height: 100%;
display: block;
background: #009879;
border-radius: 50%;
transform: scale(0);
transition: transform 0.15s;
}
.radio__input:checked + .radio__radio::after {
transform: scale(1);
}
有人知道如何使单选按钮开始工作吗?
解决方案
<label>
具有属性的 Afor
将在单击时切换相应的复选框/单选按钮id
。- 检查时,一个单选按钮将取消选中所有其他广播按钮
name
。 - ID 必须是唯一的。
现在,您所有的单选按钮都具有相同的 ID。除了无效之外,这还会导致单击任何单选按钮(因为它们都在<label>
with内for="myRadioId"
)将尝试单击带有 ID 的单选按钮myRadioId
。您的第一个单选按钮匹配,因此它被点击。(其他两个也匹配并不重要,因为 ID 应该只存在一次!)
解决方案:为每个单选按钮使用不同的 ID:
<label for="myRadioId1" class="radio">
<input type="radio" name="myRadioField" id="myRadioId1" class="radio__input">
<div class="radio__radio"></div>
option 1
</label><br>
<label for="myRadioId2" class="radio">
<input type="radio" name="myRadioField" id="myRadioId2" class="radio__input">
<div class="radio__radio"></div>
option 2
</label><br>
<label for="myRadioId3" class="radio">
<input type="radio" name="myRadioField" id="myRadioId3" class="radio__input" disabled>
<div class="radio__radio"></div>
disabled
</label>
(另外,他们可能也需要一个value
,这样您就可以通过查看表单数据知道最后点击了哪个。)
推荐阅读
- reactjs - React-bootstrap 类样式未在扩展弹出窗口中应用
- json - 我一直在尝试将 grails 升级到 4.0.7,但在运行应用程序时出现错误
- mysql - 如何计算周数,包括 MySQL 自季度开始以来的部分周数
- python - 如何将 cv2 图像转换为 skimage?
- python - TypeError: get_win_percentage() 接受 0 个位置参数,但给出了 1 个
- javascript - 在网页上显示生成的 Google 地图图像
- html - 如何忽略中间?
- go - 在代码库的其他部分使用在 main 中初始化的记录器
- javascript - 来自 @require 的 Tampermonkey 全局,带或不带 unsafeWindow
- wicket - 在检票口中,如何在点击后退按钮时重新初始化页面