引发服务器控件的客户端单击事件

    通过向控件的标记添加 onclick 属性,可以将客户端的单击事件添加到大多数的 ASP.NET 服务器控件中。但是,有些控件保留了 onclick 属性,用于定义与服务器事件的绑定。这些控件包括 ButtonLinkButtonImageButton 控件。在这些控件中,不能以声明方式使用 onclick 属性来向控件添加客户端脚本处理程序。

可以通过两种方式为单击事件添加客户端脚本处理程序:

  • 将控件的 OnClientClick 属性设置为要执行的脚本。这样,在呈现按钮控件时,OnClientClick 值将变成 onclick 属性。

  • 通过调用控件的 Attributes 集合的 Add 方法,用编程的方式添加 onclick 属性。

示例:

(1)下面的代码示例显示引发客户端和服务器 Click 两种事件的 Button 控件:

<asp:button id="Button1" runat="server" OnClientClick="return confirm('Ok to post?')" onclick="Button1_Click" Text="Click!" />

(2)C#

<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
    <script language="C#" runat="server">

        void Page_Load(Object sender, EventArgs e) {
           TextBox1.Attributes["onblur"]="javascript:alert('Hello! Focus lost from text box!!');";   
        }
    </script> 
</head>
<body>
    <h3>Attributes Property of a Web Control</h3>
<form runat="server"
    <asp:TextBox id="TextBox1" columns=54
     Text="Click here and then tap out of this text box"
     runat="server"/>   
</form>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/java166/article/details/4131674