submit()和onsubmit()的区别(转)

2011-03-16 10:34

最近在开发中遇到了表单提交前验证的问题,用一个普通的button按钮代替submit按钮,
在提交前触发这个button的onclick事件,在其事件中触发form的submit事件。问题出现了:
以下是出现相关代码:
<form action="http://www.baidu.com/s?wd=this.form.submit%28%29%3B&cl=3" method="post" name="form1" onsubmit="return alert('已提交!'); return false;"> 
    <table align="center" width="420px" cellPadding="2" cellSpacing="1" bgcolor="#A4B6D7"    style="word-wrap:Break-word;">                
        <tr style="cursor: hand;background:#d7e3f6" > 
            <td width="20%" align="right">条型码</td> 
            <td><input style="width:90%" type="text" name="GOODSNUM"   size="30"  maxlength="8" ></td> 
        </tr> 
        <tr> 
            <td align="center" colspan="2"> 
                <input type="button" name="save" value="保存" onclick="if((confirm('确定要提交吗?'))) this.form.submit();"/> 
            </td> 
        </tr>  
    </table> 
</form> 


却发现并没有触发form的onsubmit方法,而是直接提交了。奇怪了,难道没有这种方式无法结合form的onsubmit方法吗?
仔细想了想,既然this.form表示form这个对象,那么肯定能获取到form的属性和方法的
,就改成this.form.onsubmit();  成功!
我又查了查手册,原来submit的方法是这样解释的:
  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.

意思是说submit这个方法是不触发onsubmit时间的,如果想要触发它,需要调用
fireEvent方法。尝试一下:this.form.fireEvent('onsubmit');哈哈,果然也成功!不过这样不是多此一举吗?呵呵!

就这个小问题也搞了我将近一个小时,不过为了以后不为这个问题烦恼,这也是值得的。
this.form.submit(); //直接提交表单
this.form.onsubmit(); //调用form的onsubmit方法
this.form.fireEvent('onsubmit'); //同上,
     PS:又学到了fireEvent这个方法,

2.onsubmit()与submit() :

<sCript>
funCtion fun()
{
   alert("form_submit");
}
</sCript>

<form onsubmit="fun()">
<input type="submit" id="aaa" value="submit">   <!--能弹出form_submit-->
<input type="button" id="bbb" value="onCliCk_submit" onCliCk="doCument.forms[0].submit()">
<!--
表单会提交,但是不会运行fun() 原因是 onsubmit事件不能通过此种方式触发(在IE环境)
直接用脚本doCumetn.formName.submit()提交表单是不会触发表单的onsubmit()事件的
-->
    <input type="button" id="bb1" value="onCliCk_onsubmit" onCliCk="doCument.forms[0].onsubmit()">

<!--会触发fun()参数-->
</form>

posted on 2011-09-28 15:11 liujg 阅读(321) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2011年9月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

文章分类

文章档案

相册

收藏夹

boddiy

搜索

最新评论

阅读排行榜

评论排行榜