在C#中如果是asp控件的button有兩個click的調用,一個是OnClick,一個是OnClientClick。那么這兩者有什么區別呢,下面就來說說區別。
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Page_Load" OnClientClick="one()" />
首先你會看到這個button前面有asp:,表示是一個asp控件。
runat="server",這是表示這個控件能請求服務端,也就是后端,如果加了這句,那么后端就能直接通過ID來操作這個控件,如:賦值;后端代碼就可以寫成this.Button1.Text = "";
說會正題 onClick是執行服務器端的操作,而onClientClick是執行前端的方法操作,那么誰先執行呢,onClientClick先執行,若onClientClick中的方法返回true才會執行onClick中的后端方法。
如果讓這兩個方法同時起作用,則要注意OnClientClick=“return 方法名稱(); 若不加return,那么不管OnClientClick的返回結構是true或false,OnClick事件都會執行。
前端代碼:
所有服務器控件必須出現在 <form> 標簽內,同時 <form> 標簽必須包含 runat="server" 屬性。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication2.index" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form id="form1" runat="server"> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Page_Load" OnClientClick="return one()" /> </form> </body> </html> <script type="text/javascript"> function one() { document.getElementById("Button1").innerText = "你好"; return false; } </script>
后端:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication2 { public partial class index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button1.Text = "www"; } } }