今日已更新 133 条资讯 | 累计 37382 条内容
关于我们

e.preventDefault() vs e.stopPropagation()

Harsh vardhan Prasad 2026年08月12日 08:04 11 次阅读 来源:Dev.to

The easiest way to remember it: preventDefault() → stops the browser's default action. stopPropagation() → stops the event from moving through the DOM. event.preventDefault() It prevents the browser's built-in behavior associated with an event. Example: clicking a link. Google document.getElementById("link").addEventListener("click", (event) => { event.preventDefault(); }); Normally: Click ↓ Browser navigates to Google With preventDefault(): Click ↓ preventDefault() ↓ ❌ Browser does NOT navigate Common uses: // Form submission event.preventDefault(); // Link navigation event.preventDefault(); // Drag/drop browser behavior event.preventDefault(); event.stopPropagation() This prevents the event from bubbling up or capturing down through parent/child elements. Example: Click me parent.addEventListener("click", () => { console.log("Parent clicked"); }); child.addEventListener("click", (event) => { event.stopPropagation(); console.log("Button clicked"); }); Without stopPropagation(): Click Button ↓ Button handler ↓ Parent handler Output: Button clicked Parent clicked With stopPropagation(): Click Button ↓ Button handler ↓ stopPropagation() ↓ ❌ Parent handler doesn't receive the event The important difference Imagine: Like If you click the button: preventDefault() button.addEventListener("click", (event) => { event.preventDefault(); }); The event can still propagate: Button ↓ Anchor ↓ Card But the browser's default action (such as following the link) is prevented. stopPropagation() button.addEventListener("click", (event) => { event.stopPropagation(); }); The event doesn't continue through the DOM: Button ↓ ❌ Anchor/Card handlers But the browser's default behavior is not automatically cancelled. Can you use both? Yes. button.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); }); Now you're saying: Don't perform the browser's default action. Don't let this event reach other elements.

本文内容来源于互联网,版权归原作者所有
查看原文