FORM表單中onclick()、submit()與onsubmit()的問題


最近遇到一次處理form數據的過濾,采用了button的onclick事件來檢查,發現return false后表單仍然提交了。

於是仔細研究了下onclick、onsubmit、submit集合函數之間的關系和區別

onsubmit: 
You can override this event by returning false in the event handler.
Use this capability to validate data on the client side to prevent invalid data from being submitted to the server.
If the event handler is called by the onsubmit attribute of the form object,
the code must explicitly request the return value using the return function,
and the event handler must provide an explicit return value for each possible code path in the event handler function.
The submit method does not invoke the onsubmit event handler.

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.

首先生成一個form

<form action="#" method="POST" name="A" onsubmit="return X();">
<input type="text" value="" />
<input onclick="Y()" type="submit" value="提交" />
</form>

自己寫X()、Y()函數,我們會發現,這幾個函數的執行順序

1) onclick: Y();

2) onsubmit: X();

3) submit();

也就是說

只要 onclick 未 return false 那么就繼續執行 onsubmit

只要 onsubmit 未return false 那么表單就被提交出去了

另外一點寫法上注意一定要 “return X();” 才能取得函數的返回值,否則只是調用函數,返回值未被傳遞

正確寫法:
<input type=submit onclick=”return X();”>
//X() 返回false后,form的submit會被終止

錯誤寫法:
<input type=submit onclick=”X()”>

//X() 返回false后未傳遞給onclick事件,form的submit會繼續


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM