现在的位置: 首页 > 综合 > 正文

JS代码,将终端用户(Web 页面的查看者)的计算机时间置于一个按钮 Web 服务器控件上

2013年06月02日 ⁄ 综合 ⁄ 共 2356字 ⁄ 字号 评论关闭
将终端用户(Web 页面的查看者)的计算机时间置于一个按钮 Web 服务器控件上。以下代码显示了如何完成该任务:

<%@ Page Language="C#" %>

<script runat="server">
    protected 
void Button1_Click(object sender, EventArgs e)
    
{
        Response.Write(
"回发!");
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>使用 JavaScript</title>
</head>
<body onload="javascript:document.forms[0]['Button1'].value=Date();">
    
<form id="form1" runat="server">
    
<div>
        
<asp:Button ID="Button1" runat="server" Text="按钮" 
         OnClick
="Button1_Click" Font-Bold="True" Font-Names="Verdana" 
         Font-Size
="Larger" />
    
</div>
    
</form>
</body>
</html>

在此小段代码中,要注意按钮的一些属性在被发送到客户端浏览器之前是如何指定给服务器端的。本例中,按钮上文本的字体被更改为具有特定大小的粗体 Verdana。客户端接收到按钮的 HTML 代码后,客户端 JavaScript 即会将该按钮的文本更改为终端用户计算机上的当前时间。针对整个页面生成的 HTML 代码如下:

 1<html xmlns="http://www.w3.org/1999/xhtml" >
 2<head><title>
 3   使用 JavaScript
 4</title></head>
 5<body onload="javascript:document.forms[0]['Button1'].value=Date();">
 6    <form name="form1" method="post" action="Default.aspx" id="form1">
 7<div>
 8<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
 9 value="/wEPDwUKMTY3NzE5MjIyMGRkVUxVdzEWBhD7U89t7JKIkQc6Cko=" />
10</div>
11
12    <div>
13        <input type="submit" name="Button1" value="" id="Button1" 
14         style="font-family:Verdana;font-size:Larger;font-weight:bold;" />
15    </div>
16    
17<div>
18
19   <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" 
20    value="/wEWAgK394SHCAKM54rGBtsX8d2S8MO7sf02DOAiquFyBkeY" />
21</div></form>
22</body>
23</html>
24

在本例中,我们通过 onload 属性将一些 JavaScript 直接置于页面的 <body> 元素中。对于 onload 属性的值,我们特意指向了第一个 <form> 节(因为在 HTML 中可能会有多个 form)中名为 Button1 的 HTML 元素。

虽然使用此方法来添加一些 JavaScript 以便与 ASP.NET Web 服务器控件配合使用很简单,但是我们也可以很容易地将一个 JavaScript 命令添加到按钮本身,如以下部分代码示例所示:

 

 1<%@ Page Language="C#" %>
 2
 3<script runat="server"> 
 4    protected void Page_Load(object sender, EventArgs e)
 5    {
 6        Button1.Attributes.Add("onclick"
 7           "javascript:alert('多加注意!!!')");
 8    }

 9
</script>
10
11<html xmlns="http://www.w3.org/1999/xhtml" >
12<head runat="server">
13    <title>使用 JavaScript</title>
14</head>
15<body>
16    <form id="form1" runat="server">
17    <div>
18        <asp:Button id="Button1" runat="server" Font-Bold="True" 
19         Font-Names="Verdana" Font-Size="Larger" 
20         Text="单击我!"></asp:Button>
21    </div>
22    </form>
23</body>
24</html>
25

<script>
alert(Date());
</script>
显示客户端时间!!!

抱歉!评论已关闭.