form表單下的按鈕在沒有指定type類型的時候,如果我們同時給其添加了點擊事件的話。會發現我們在點擊的時候回默認的把表單也給提交了。如:
<script type="text/javascript"> function validate(){ alert("test"); }</script><button id="validate" onclick="validate();"></button>
於是我大膽猜測應該是form下的button 按鈕在沒有明確的給出type類型時,會有一個默認值爲:type=”submit”.
帶着這種猜測於是開始查找資料,在:https://www.w3.org/TR/2011/WD-HTML5-20110525/the-button-element.html#attr-button-type驗證了我的猜測:
The type attribute controls the behavior of the button when it is activated. It is an enumerated attribute. The following table lists the keywords and states for the attribute — the keywords in the left column map to the states in the cell in the second column on the same row as the keyword.Keyword State Brief descriptionsubmit Submit Button Submits the form.reset Reset Button Resets the form.button Button Does nothing.**The missing value default is the Submit Button state.**
解決辦法很明顯了:如果該按鈕的作用不是爲了提交表單的話,我們給其加上type屬性就行了:
<button id="validate" type="button" onclick="validate();"></button>