问题
This is the code from .aspx file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Login Again</title>
<script type="text/javascript">
function Validate() {
if (document.getElementById("txtLogin").value == "") {
alert("Enter login name.");
}
if (document.getElementById("<%=txtLogin.ClientID%>").value == "") {
alert("Enter login name.");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtLogin" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Login" OnClientClick="Validate()" />
</form>
</body>
</html>
-
In function Validate() I can access textbox using Id of control i.e.;
getElementById("txtLogin")
so should I use the second approach which is accessing control throughcontrol.ClientID
and why? -
My first understanding was that to access server control I have to use this syntax
<%= %>
but now I come to know from this example that I can access server side control simply throughgetElementById("ID-of-control")
.
答案
The ID generated in the final HTML is not guaranteed to remain the same as the one in your aspx source. When you'll put the controls inside naming containers the ID will have prepended one or several parent ids to ensure its uniqueness. The ClientId property will always give you the final form of the ID attribute as it ends up in the HTML so it's always recommended to use that in your javascript.