document.getElementById(“”);给空

问题描述 投票:2回答:1

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

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;
}
javascript c# asp.net .net asp.net-ajax
1个回答
0
投票

OP在评论中表示...

是其外部js文件

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

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

有多种解决方法,第一种可能不理想,但是将脚本放入.aspx.ascx文件中。

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


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

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

由于getElementsByClassName返回一个元素数组(因为页面上的多个元素可能具有相同的类),以上内容将返回该数组中的第一项。如果您的代码更复杂,则需要相应地对其进行修改]


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

var errIcon = txtBox.nextElementSibling;
© www.soinside.com 2019 - 2024. All rights reserved.