单选按钮标签点击异常:点击第二、三标签选中第一个按钮
问题描述
我有三个name属性相同的radio按钮:点击第一个按钮的单选框可选中该按钮;点击第二个、第三个按钮的单选框时,也能分别选中对应按钮。但点击第二个或第三个按钮的label标签时,会自动选中第一个按钮。
我曾尝试修改第一个div的宽度为100px,但问题仍未解决。
代码示例
HTML
<div id="Div_For_All_Players"> {/* DIV for all players */} <div id="Div_For_First_Player"> <input name="Player_Playing" type="radio" value="One_Player" id="Radio_1" className="Radio_Buttons" onClick={Player_One_Clicked}></input>{/* Radio Buttons for How Many Players */} <label htmlFor="Radio_1" id="Label_1" className="First_Button">One Player</label>{/* Labels for One Player */} </div> <div id="Div_For_Second_Player"> <input name="Player_Playing" type="radio" value="Two_Players" id="Radio_2" className="Radio_Buttons" onClick={Player_Two_Clicked}></input>{/* Radio Buttons for How Many Players */} <label htmlFor="Radio_1" id="Label_2" className="Second_Button">Two Players</label>{/* Labels for Two Players */} </div> <div id="Div_For_Third_Player"> <input name="Player_Playing" type="radio" value="Three_Players" id="Radio_3" className="Radio_Buttons" onClick={Player_Three_Clicked} defaultChecked={true}></input>{/* Radio Buttons for How Many Players */} <label htmlFor="Radio_1" id="Radio_3_label" className="Third_Button">Three Players</label>{/* Label for Three Players */} </div> </div>
CSS
#Div_For_First_Player { text-align: left; overflow: hidden; line-height: 1em; position: relative; bottom: -20px; width: 100px; } #Div_For_Second_Player { display: flex; justify-content: center; text-align: center; } #Div_For_Third_Player { text-align: right; position: relative; top: -20px; float: right; }
解决方案
问题根源在于label标签的htmlFor属性配置错误:第二个和第三个label的htmlFor都指向了第一个radio的idRadio_1,导致点击这两个label时会触发第一个radio的选中状态。
只需将对应label的htmlFor属性改为匹配各自关联的radio的id即可:
- 第二个label("Two Players")的
htmlFor改为Radio_2 - 第三个label("Three Players")的
htmlFor改为Radio_3
修正后的HTML片段:
<div id="Div_For_Second_Player"> <input name="Player_Playing" type="radio" value="Two_Players" id="Radio_2" className="Radio_Buttons" onClick={Player_Two_Clicked}></input> <label htmlFor="Radio_2" id="Label_2" className="Second_Button">Two Players</label> </div> <div id="Div_For_Third_Player"> <input name="Player_Playing" type="radio" value="Three_Players" id="Radio_3" className="Radio_Buttons" onClick={Player_Three_Clicked} defaultChecked={true}></input> <label htmlFor="Radio_3" id="Radio_3_label" className="Third_Button">Three Players</label> </div>
修改后,点击每个label都会正确选中对应的radio按钮,与点击单选框本身的效果一致。
内容的提问来源于stack exchange,提问作者Malik4033
相关产品推荐
相关产品推荐

