Difference between ID and control.ClientID OR why use control.ClientID if I can access control through ID

 问题

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 through control.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 through getElementById("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.

猜你喜欢

转载自www.cnblogs.com/chucklu/p/10682960.html
今日推荐