添加ID选择器后Razor复选框无法切换状态的问题及解决
问题:Razor复选框手动添加ID后无法切换状态
在使用Razor生成自定义样式复选框时,手动为<input>添加id="chkb"后,复选框被锁定为开启状态,无法点击切换。尚未接入jQuery,后台无报错,仅添加ID就出现该问题。
可用代码(未手动添加ID时正常)
<div class="custom-control custom-checkbox"> <input class="custom-control-input" type="checkbox" asp-for="myReportModel.ReportType_PushReport"> <label class="custom-control-label" asp-for="myReportModel.ReportType_PushReport"></label> </div>
不可用代码(添加ID后锁定)
<div class="custom-control custom-checkbox"> <input class="custom-control-input" type="checkbox" id="chkb" asp-for="myReportModel.ReportType_PushReport"> <label class="custom-control-label" asp-for="myReportModel.ReportType_PushReport"></label> </div>
解决方法:同步label的for属性与input的ID
自定义样式复选框(custom-control-checkbox)的交互依赖<label>的for属性与<input>的id关联。手动添加input的ID后,label的for属性未同步更新,导致点击label无法触发input的状态切换(原生input被自定义样式隐藏,用户实际点击的是label)。只需为label添加for="chkb",与input的ID对应即可恢复正常:
<div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="chkb" asp-for="myReportModel.chkParams.ReportType_PushReport" checked="@(Model.myReportModel.chkParams.ReportType_PushReport == true)"> <label class="custom-control-label" asp-for="myReportModel.chkParams.ReportType_PushReport" for="chkb"></label> </div>
内容的提问来源于stack exchange,提问作者Bill
相关产品推荐
相关产品推荐

