萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

HTML button 默認 type=submit 導致表單誤提交問題

問題現象

在彈窗中放置一個 <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 同現代瀏覽器,提交表單

最佳實踐

  1. 強制規範:所有 <button> 必須顯式聲明 type="button|submit|reset"
  2. ESLint 規則:啟用 html/button-has-type 或 react/button-has-type 自動檢查
  3. 代碼審查清單:檢查表單內按鈕是否漏寫 type
  4. 框架組件封裝:封裝 <Btn type="button"> 組件,默認 type="button"

擴展:form 相關默認行為速查

元素/屬性默認行為備註
<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% 杜絕此類問題。

copyright © 萬盛學電腦網 all rights reserved