submit 和onsubmit 的區別
阿新 • • 發佈:2018-12-21
最近在開發中遇到了表單提交前驗證的問題,用一個普通的button按鈕代替submit按鈕, 在提交前觸發這個button的onclick事件,在其事件中觸發form的submit事件。問題出現了: 以下是出現相關程式碼: Java程式碼
- <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=
- <input type="button" name="save" value="儲存" onclick="if((confirm('確定要提交嗎?'))) this.form.submit();"/>
- </td>
- </tr>
- </table>
- </form>
<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這個方法