js触发asp.net的Button的Onclick事件

在asp.net引入事件驱动之后,在一个页面上很容易解决多个按钮触发不同事件的问题,避免了在asp中需要多个form或者通过js脚本来控制 的麻烦。

asp.net带来便利的同时,也带来一个问题。在实际应用中一个页面存在多个按钮的情况并不多。用户习惯于在输入框输入内容之后,直接按回车就提 交表单了。由于asp.net采用的是事件驱动模式,所以默认用户按回车并没有触发按钮的onclick事件。用户按回车也不是没有提交表单,通过httpwath可以看到,实际上页面表单是提交到了form下的action页 面,只不过没有触发onclick事件而已。

在asp.net事件驱动模式下面,要实现通过回车来触发事件,必须要借助js脚本来实现。

在asp.net的aspx页面中,form的代码:
<form id="form1" runat="server">

但在访问页面的源代码中可以看到:
< form   name ="form1"   method ="post"   action ="Default.aspx"   id ="form1" >

所以在输入框默认直接按回车,其实就是把表单提交到了form的action对应的页面,而并没有触 发任何事件。

奇怪的地方:当一个aspx页面上没 有使用web控件 的时候,在输入框里按回车,默认是不会触发任何一个button按钮的onclick事件;但当页面上 有使用web控件 的时候,在输入框里按回车,默认会触发第一个 button的onclick事件 。【这里的第一指页面代码 中最先出现的button控件,包括web控件内的button控件】

下面说说如何通过js来触发button按钮的onclick事件。

默认的button控件,在html中的代码是这样的:
< input   type ="submit"   name ="Button1"   value ="Button"   id ="Button1"   />

实际 上点击这个button触发的onclick事件调用了一个js脚本: __doPostBack(eventTarget, eventArgument)

button 控件有个属性:UseSubmitBehavior,默认是true,当你修改为false的时候,再去看html的源代码,就能清楚的看到调用的js脚 本函数。
< input   type ="button"   name ="Button1"   value ="Button"   onclick ="javascript:__doPostBack('Button1','')" id ="Button1"   />

生成的js脚本:
<script type="text/javascript"> 
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>

了解了这块内容,要处理输入框按回车触发button的onclick事件就简单的多了,就是截获输入框按回车的这个动 作,然后通过js调用 __doPostBack 这个函数就OK了

输入框:
< input   name ="TextBox1"   type ="text"   id ="TextBox1"   onkeydown ="return KeyDown('Button1');"   />
< input   type ="submit"   name ="Button1"   value ="Button"   id ="Button1"   />

js脚本
        function KeyDown(btn) {
            if (event.keyCode != 13) //按键不是enter键
          {
                return;
            }
            else //按键是enter键
            {
                try {
                    __doPostBack(btn, '');
                    return false;
                }
                catch (e) {
                    alert(e);
                    return;
                }
            }
        }

如果要输入框和button控件是在web控件里的,就需要特别注意:
控件中的button控件生成的html代码:
< input   type ="submit"   name ="WUC11$Button2"   value ="Button"   id ="WUC11_Button2"   />
__doPostBack中用到的是input按钮的name属性,web控件中button,在生成的html代码里会加上控件的ID,所以传递的 button名称不要写错了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值