在 JSP/HTML 中使用 <button> 或 <input type="button"> 時,若未顯式指定 type="button",瀏覽器默認視為 type="submit",導致表單意外提交或提交邏輯衝突,表現為「點擊無反應」或「重複提交」。
<form action="/submit" method="post">
<c:forEach items="${list}" var="item">
<button onclick="edit(${item.id})">編輯</button>
<!-- 缺少 type="button",默認 submit -->
</c:forEach>
<input type="submit" value="保存" />
</form>
點擊「編輯」按鈕會觸發表單提交,而非執行 edit(),導致頁面跳轉/刷新,JS 邏輯中斷。
<button type="button" onclick="edit(${item.id})">編輯</button>
<!-- 或 -->
<input type="button" value="編輯" onclick="edit(${item.id})" />
| 類型 | 行為 | 適用場景 |
|---|---|---|
type="submit" | 提交表單(默認) | 表單唯一提交按鈕 |
type="reset" | 重置表單 | 清空/恢復默認值 |
type="button" | 無默認行為,純 JS 掛載 | 編輯、刪除、彈窗等自定義操作 |
type="button":除非確實要提交表單,所有功能性按鈕都加上。<input type="button">:語義更清晰,默認即為按鈕,無需記憶 type 屬性。event.preventDefault() 作為雙重保險。<form id="mainForm" ...>...</form>
<form id="searchForm" ...>...</form>
<button type="button" onclick="document.getElementById('searchForm').submit()">搜索</button>
<button type="submit" form="mainForm">保存</button>
<!-- HTML5 form 屬性指定歸屬表單 -->
明確按鈕類型,是避免表單提交邏輯混亂的基礎,也是前端代碼規範的必檢項。