`event.preventDefault()` 取消瀏覽器對事件的**預設行為**:表單提交、連結跳轉、右鍵選單、輸入法組合等。不阻止事件冒泡 (需用 `stopPropagation()`)。
<!DOCTYPE html>
<html>
<head>
<title>preventDefault 範例:搜尋表單驗證</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$("#myform").submit(function(e) {
if ($("#search").val().trim() === "") {
alert("搜尋內容不能為空");
e.preventDefault(); // 取消表單提交
}
});
});
</script>
</head>
<body>
<form action="https://www.google.com/search" method="get" id="myform">
<input type="text" name="q" id="search" size="38" placeholder="輸入關鍵字..." />
<input type="submit" value="搜尋" />
</form>
</body>
</html>
// 1. 匿名函式參數 (推薦)
$("#form").submit(function(e) { e.preventDefault(); });
// 2. 箭頭函式 (需用 event.currentTarget)
$("#form").submit((e) => { e.preventDefault(); });
// 3. 內聯事件 (不推薦)
<form onsubmit="return handleSubmit(event)">
function handleSubmit(e) { if (!valid) { e.preventDefault(); return false; } }
| 元素/事件 | 預設行為 | preventDefault() 效果 |
|---|---|---|
<a> click | 跳轉 href | 阻止跳轉 |
<form> submit | 送出表單 | 阻止送出 |
<input> keydown | 輸入字元 | 阻止字元輸入 (可做輸入過濾) |
contextmenu | 顯示右鍵選單 | 阻止右鍵選單 |
dragstart | 開始拖曳 | 禁止拖曳 |
wheel (passive: false) | 頁面捲動 | 阻止捲動 (需 passive:false) |
touchmove | 觸控捲動 | 阻止捲動 (需 passive:false) |
| 寫法 | 阻止預設行為 | 阻止冒泡 | 停止當前函式後續代碼 |
|---|---|---|---|
e.preventDefault() | ✅ | ❌ | ❌ |
e.stopPropagation() | ❌ | ✅ | ❌ |
e.stopImmediatePropagation() | ❌ | ✅ (含同元素其他 handler) | ❌ |
return false (jQuery handler) | ✅ | ✅ | ✅ |
return false (原生 onxxx) | ✅ | ❌ | ✅ |
<style>
#customMenu { position: fixed; display: none; background: white; border: 1px solid #ccc; box-shadow: 0 2px 8px rgba(0,0,0,0.15); padding: 5px 0; z-index: 9999; min-width: 150px; }
#customMenu div { padding: 8px 15px; cursor: pointer; white-space: nowrap; }
#customMenu div:hover { background: #f0f0f0; }
</style>
<div id="customMenu">
<div data-action="copy">複製</div>
<div data-action="paste">貼上</div>
<hr style="margin:5px 0;border:none;border-top:1px solid #eee">
<div data-action="inspect">檢查元素</div>
</div>
<script>
$(document).on("contextmenu", function(e) {
e.preventDefault(); // 關鍵:阻止原生右鍵選單
$("#customMenu").css({ left: e.pageX, top: e.pageY }).show();
}).on("click", function() {
$("#customMenu").hide();
});
$("#customMenu").on("click", "div", function() {
var action = $(this).data("action");
console.log("自訂選單動作:", action);
$(this).parent().hide();
});
</script>
為提升捲動效能,現代瀏覽器預設 `touchstart`/`wheel` 為 `passive: true` (不阻塞主執行緒)。若需在這些事件中呼叫 `preventDefault()`,必須顯式註冊:
element.addEventListener('touchmove', function(e) {
if (shouldPrevent) e.preventDefault();
}, { passive: false }); // 關鍵:聲明非被動