submit()和onsubmit()的区别

本文探讨了使用普通按钮触发表单提交时遇到的问题及解决方法。通过调整代码,实现了在点击按钮时先触发确认对话框,再决定是否提交表单,并确保能够执行form的onsubmit方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在开发中遇到了表单提交前验证的问题,用一个普通的button按钮代替submit按钮,
在提交前触发这个button的onclick事件,在其事件中触发form的submit事件。问题出现了:
以下是出现相关代码:
Java代码 复制代码
  1. <formaction= "http://www.baidu.com/s?wd=this.form.submit%28%29%3B&cl=3" method= "post" name= "form1" οnsubmit= "returnalert('已提交!');returnfalse;" >
  2. <tablealign= "center" width= "420px" cellPadding= "2" cellSpacing= "1" bgcolor= "#A4B6D7" style= "word-wrap:Break-word;" >
  3. <trstyle= "cursor:hand;background:#d7e3f6" >
  4. <tdwidth= "20%" align= "right" >条型码</td>
  5. <td><inputstyle= "width:90%" type= "text" name= "GOODSNUM" size= "30" maxlength= "8" ></td>
  6. </tr>
  7. <tr>
  8. <tdalign= "center" colspan= "2" >
  9. <inputtype= "button" name= "save" value= "保存" οnclick= "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" οnsubmit="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="保存" οnclick="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这个方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值