document.getElementById("<%= errorIcon.ClientID %>");给空

document.getElementById("<%= errorIcon.ClientID %>"); is giving null

我正在尝试对我的注册页面进行服务器端 + 客户端验证。当我的 TextBox 控件失去焦点(onBlur)时,我想调用一个 JS func。

aspx页面中的代码

<div id="nameDiv">              
    <asp:UpdatePanel ID="updatePanelName" runat="server">
        <ContentTemplate>
            <asp:Label ID="labelName" runat="server" Text="Enter Your Name"></asp:Label>
            <asp:TextBox ID="textBoxName" runat="server" placeholder="Enter Your Name" 
              onBlur="check(this)"></asp:TextBox>
            <i class="fa fa-exclamation-circle errorSign" id="errorIcon" runat="server"></i>                      
            <asp:Label ID="labelNameError" runat="server" Text="Name can't be blank" ForeColor="Red"> 
              </asp:Label>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>

Javascript代码

function check(txtBox) {
    var errIcon = document.getElementById("<%= errorIcon.ClientID %>");
    txt = txtBox.value;
    if (txt.length < 1)
        errIcon.style.visibility = "visible";
}

CSS

input[type=text] {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display:inline-block;
    position:relative;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}


.errorSign{
    position:absolute;
    margin-right:30px;
    left:1050px;
    top:220px;
    visibility:hidden;
}

OP 通过评论表示...

yes its an external js file

失败的原因是 .js 文件未被 ASP.Net 处理,将被发送到浏览器而不做任何更改。这意味着浏览器正在接收与写入完全相同的行...

var errIcon = document.getElementById("<%= errorIcon.ClientID %>");

有多种方法可以解决此问题...第一种方法可能不太理想,但可以将脚本放入您的 .aspx.ascx 文件中。

这意味着脚本(作为 ASP.Net 已处理页面的一部分)将具有控件的实际 id,而不是 <%=..%>.


第二种可能更好的方法是直接使用 class 名称,而不是 id...

var errIcon = document.getElementsByClassName("errorSign")[0];

作为getElementsByClassName return一个元素数组(因为页面上的多个元素有可能具有相同的class)以上将return该数组中的第一项。如果你的代码比较复杂,你需要做相应的修改


另一个选项(感谢 @epascarello)是使用 nextElementSibling,但如果您出于某种原因更改 HTML(例如重新设计页面),这可能会中断)...

var errIcon = txtBox.nextElementSibling;