<%@ 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屬性。聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com