javascript类型错误:txt为空

javascript类型错误:txt为空,javascript,Javascript,我有一个javascript代码 <head runat="server"> <title></title> <script> function kk() { var txt = document.getElementById(<%=txt.ClientID%>); if (txt.value == "rd1") { docu

我有一个javascript代码

<head runat="server">
    <title></title>
    <script>
        function kk() {
            var txt = document.getElementById(<%=txt.ClientID%>);
            if (txt.value == "rd1") {
                document.getElementById("rd1").checked = true;
            }
            console.log("kk");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txt" onchange="kk()" runat="server"></asp:TextBox>
            <br />
            <asp:RadioButton ID="rd1" runat="server" />
            <asp:RadioButton ID="ed2" runat="server" />
        </div>
    </form>
</body>

函数kk(){
var txt=document.getElementById();
如果(txt.value==“rd1”){
document.getElementById(“rd1”).checked=true;
}
控制台日志(“kk”);
}

但是显示错误


乍一看,我可以看出代码中有一个疏忽。而不是:

var txt = document.getElementById(<%=txt.ClientID%>);
getElementById()
接受字符串。你应该写:

document.getElementById("<%=txt.ClientID%>");
document.getElementById(“”);
引用

否则,
txt.ClientID
的值将被解析为变量名。由于不存在该名称的变量,
未定义的
将被传递到
getElementById()
,并返回
null

if (txt !== null && txt.value == 'rd1') {
    // do something
}
document.getElementById("<%=txt.ClientID%>");