ASP.NET 实现单选按钮联动禁用及null属性读取报错排查
问题根因
你的报错确实是元素引用错误导致的。ASP.NET Web Form 中带 runat="server" 的控件渲染到前端时,会自动根据父容器层级生成拼接后的客户端ID,你写的服务器端ID this、that 不会直接作为DOM的id属性值,因此 document.getElementById("this") 拿到的是null,访问checked属性就会抛出「cannot read the property of a null」错误。
除此之外你的代码还有两个问题:
- 仅在页面加载完成时执行了一次判断,没有监听
this单选框的选中事件,无法实现选中后动态启用that的需求 - if判断语句缺少闭合右括号,存在语法错误
修复方案
最简单的解决方式是给单选框添加 ClientIDMode="Static" 属性,强制渲染后的客户端ID和服务器ID保持一致,同时补充选中事件监听逻辑,修正后的完整代码如下:
<asp:Content ID="Content2" runat="server"> <div><asp:RadioButton ID="this" runat="server" ClientIDMode="Static" GroupName="radioGroup" /></div> <div><asp:RadioButton ID="that" runat="server" ClientIDMode="Static" GroupName="radioGroup" /></div> <script type="text/javascript"> $(document).ready(function () { // 初始化默认禁用that $("#that").prop("disabled", true); // 监听this的选中变化 $("#this").on("change", function() { if ($(this).is(":checked")) { $("#that").prop("disabled", false); } else { $("#that").prop("disabled", true); } }); }); </script> </asp:Content>
注:两个单选框添加相同的
GroupName属性是为了保证二者是互斥的单选关系,符合常规使用逻辑,你可以根据实际需求调整。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

