ID和control.ClientID为什么使用control.ClientID之间的区别,如果我可以通过ID访问控制 [英] Difference between ID and control.ClientID OR why use control.ClientID if I can access control through ID

查看:131
本文介绍了ID和control.ClientID为什么使用control.ClientID之间的区别,如果我可以通过ID访问控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从.aspx文件code

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>


  • 在功能的验证()我可以
    使用控制ID访问文本
    即; 的getElementById(txtLogin)等等
    我应该使用第二种方法
    这是访问控制通过
    control.ClientID 为什么?

    我的第一个理解是,要
    访问服务器控件我必须使用
    此语法&LT;%=%GT; ,但现在我来
    从这个例子就知道我可以
    访问服务器端控件只是
    通过
    的getElementById(ID-的控制)

    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").

    推荐答案

    在最终的HTML生成的ID不能保证保持一样的一个在你的aspx来源。当你会把命名容器内部的控件ID将有prepended一个或几个家长ID,以保证它的唯一性。 ClientID属性将永远给你的ID属性的最终形式,因为它在HTML结束了,所以它总是建议使用在你的JavaScript。

    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.

    这篇关于ID和control.ClientID为什么使用control.ClientID之间的区别,如果我可以通过ID访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆