focus 专栏

--专注于.NET Web开发技术
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

html 的 image button 自动提交 form

Posted on 2007-12-06 11:35  focus  阅读(3613)  评论(2编辑  收藏  举报
今天在项目的代码中看到这么一段:
<HTML>
<BODY>
<FORM name="frmData" onsubmit="Login()">
<INPUT type="image" src="submit.gif" name="imgSubmit" value="" />
</FORM>
</BODY>
<script>
 function Login()
 {
  alert('hello');
 }
</script>
</HTML>
奇怪了,这个登陆按钮没写任何代码触发 form 的提交,但是我们的程序又是怎样正确 work 的?
我想是不是在另外的地方用 js 给这个按钮绑定了 onclick 事件?
于是我把代码拷下来,生成了上面的简化版.
在测试中点击图片后,成功弹出 hello.
查阅资料发现,image button 可以自动触发 form 的 onsubmit 事件.
另外通过用 button 测试,还发现一个现象:
<input type="button" name="btnSubmit" value="submit" onclick="frmData.submit()"/>
这样 form 是提交了,但是不会进入 Login 方法.
相关资料解释:
The submit method does not invoke the onsubmit event handler. Call the onsubmit event handler directly. When using Microsoft® Internet Explorer 5.5 and later, you can call the fireEvent method with a value of onsubmit in the sEvent parameter.
要这样才能调用到 Login 方法:
<input type="button" name="btnSubmit" value="submit" onclick="frmData.fireEvent('onsubmit')"/>
或者
<input type="button" name="btnSubmit" value="submit" onclick="frmData.onsubmit()"/>