OnClick是button的伺服器端事件 OnClientClick是button的用戶端事件 一般我們用 OnClientClick驗證我們的提交資料,但是這個一定要返回ture或者false,即一定要加上return,否則OnClick失效。當返回false時OnClick伺服器端事件才被中止,當你的js驗證有錯誤,也會跳過驗證,直接執行伺服器端事件OnClientClick。為了避免這樣的錯誤,可以考慮用服務端驗證這樣就省去了OnClientClick事件,就不用考慮和OnClick的衝突了。但是從效能上,服務端驗證,耗費了伺服器資源,呵呵,一般是沒問題的,只是和用戶端驗證比較而已,各有所長,各有所短。 例如下: try2.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="try2.aspx.cs" Inherits="try2" %> <!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>無標題</title> <script type="text/javascript"> function checkname() { var name=document.getElementById('TextBox1'); if(name.value=="") { alert("姓名不可為空!"); return false; } } </script> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td> 姓名:</td> <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td> </tr> <tr> <td > </td> <td > <asp:Button ID="Button1" runat="server" Text="確定" OnClientClick="return checkname()" OnClick="Button1_Click" /></td> </tr> </table> </div> </form> </body> </html> 後台代碼:try2.aspx.cs: using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class try2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { Response.Write("最後執行了!"); } } 可測試發現如果try2.aspx 中OnClientClick="checkname()" ,沒有"return ",用戶端和伺服器端都執行操作。 所以上例應帶“return”,當姓名輸入為空白時,不至於執行伺服器端的"Button1_Click"事件。即OnClientClick="return checkname()" |