Button 控件的 OnClientClick 和 OnClick 事件执行顺序问题

 

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>
        &nbsp;
        <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()"     。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值