在彈窗中放置一個 <button>添加調查問卷</button>,點擊後彈窗意外關閉/頁面跳轉。經排查發現:button 未指定 type 時,默認 type="submit",會觸發所屬表單提交。
<button class="btn btn_set_wj" onclick="add_q()">添加調查問卷</button>
<button class="btn btn_set_wj" type="button" onclick="add_q()">添加調查問卷</button>
根據 HTML 標準:
<button> 默認 type="submit"<input type="button"> 默認即為 button,不提交<input type="submit"> 才提交表單| 瀏覽器 | 無 type 時行為 |
|---|---|
| Chrome / Firefox / Edge / Safari (現代) | 在 form 內按下 → 提交表單 |
| IE ≤ 8 | 某些情況下不提交(但不可依賴) |
| 移動端 WebView | 同現代瀏覽器,提交表單 |
<button> 必須顯式聲明 type="button|submit|reset"html/button-has-type 或 react/button-has-type 自動檢查<Btn type="button"> 組件,默認 type="button"| 元素/屬性 | 默認行為 | 備註 |
|---|---|---|
<button> |
type="submit" | 必須顯式寫 type="button" |
<input> |
type="text" | 無 type 時為文本框 |
<form> |
method="GET" | 建議顯式寫 method="POST" |
<form> |
enctype="application/x-www-form-urlencoded" | 上傳文件需改 multipart/form-data |
| Enter 鍵 | 觸發首個 submit 按鈕 | 可用 event.preventDefault() 阻止 |
「button 沒寫 type=button 導致提交」是前端開發中極高頻的低級錯誤。養成「寫 button 必寫 type」的肌肉記憶,配合 Lint 工具攔截,能 100% 杜絕此類問題。