submit 和onsubmit 的区别

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

猜你喜欢

转载自blog.csdn.net/qq_44910624/article/details/89386856
今日推荐