时间:2021-07-01 10:21:17 帮助过:15人阅读
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<script type="text/javascript">
function GetValue()
{
<SPAN style="COLOR: #0080c0"><STRONG>var t=document.getElementById('<%= TextBox1.ClientID %>');</STRONG></SPAN>
t.innerText=2;
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></div>
<input type="button" runat="server" id="button1" onclick="GetValue();" value="赋值" />
</form>
</body>
</html>
有人会问了:var t=document.getElementById("TextBox1");不是也运行的好好的吗?
答案:在一般的aspx中ID=ClientID(前提是你自己已经设置好了ID值)
看下面代码,设置了模板页
代码如下:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function GetValue()
{
<SPAN style="COLOR: #0080c0"><STRONG>document.write('<%= TextBox1.ClientID %>')</STRONG></SPAN>
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input type="button" runat="server" id="button1" onclick="GetValue();" value="赋值" />
</asp:Content>
页面显示了<SPAN style="COLOR: #0080c0"><STRONG>ctl00_ContentPlaceHolder1_TextBox1</STRONG></SPAN>。即TextBox1.ClientID =ctl00_ContentPlaceHolder1_TextBox1。
此时把代码改成
代码如下:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function GetValue()
{
<SPAN style="COLOR: #0080c0"><STRONG><SPAN style="TEXT-DECORATION: line-through">var t=document.getElementById("TextBox1");</SPAN></STRONG></SPAN>
t.innerText=2;
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input type="button" runat="server" id="button1" onclick="GetValue();" value="赋值" />
</asp:Content>
出错了,t=null,也就是找不到TextBox1,所以需要改成<SPAN style="COLOR: #0080c0"><STRONG>var t=document.getElementById('<%=TextBox1.ClientID%>');</STRONG></SPAN>
3、综述
view sourceprint?1 对于服务器控件,在客户端调时使用ClientID属性,在服务端时使用ID属性。