| 方法 | 作用對象 | 作用 | 典型場景 |
|---|---|---|---|
preventDefault() | 事件的默認行為 | 阻止瀏覽器默認行為(跳轉、提交、選中等) | 阻止 `` 跳轉、阻止表單提交、阻止右鍵菜單、阻止輸入框默認輸入 |
stopPropagation() | 事件傳播流程 | 阻止事件冒泡(或捕獲)向父元素傳遞 | 點擊子元素不觸發父元素同類事件、事件代理中精確控制觸發範圍 |
<a href="https://www.baidu.com" id="testLink">百度</a>
<script>
var link = document.getElementById('testLink');
link.onclick = function(e) {
e = e || window.event; // 兼容 IE
alert('我的鏈接是:' + this.href + ',但我不會跳轉。');
// 標準瀏覽器
if (e.preventDefault) {
e.preventDefault();
}
// IE 8-
else {
e.returnValue = false;
}
return false; // 兼容舊版瀏覽器/內聯處理器
};
</script>
function stopDefault(e) {
e = e || window.event;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
return false;
}
當一個元素觸發事件(如 `click`)時,該事件會依次向上傳播至所有祖先元素(`parent` → `body` → `html` → `document` → `window`),並在每層觸發綁定的同類事件處理器。這就是「事件冒泡」。
利用冒泡特性,將事件處理器綁定在父容器上,通過 `event.target` 判斷具體觸發元素,實現「一個處理器管理多個子元素」,適合動態添加元素、大量同類元素場景。
<div id="parent1" onclick="alert('parent1')" style="width:250px;background:yellow">
<p>This is parent1 div.</p>
<div id="child1" onclick="alert('child1')" style="width:200px;background:orange">
<p>This is child1.</p>
</div>
</div>
<div id="parent2" onclick="alert('parent2')" style="width:250px;background:cyan">
<p>This is parent2 div.</p>
<div id="child2" onclick="doSomething(this, event)" style="width:200px;background:lightblue">
<p>This is child2. Will bubble.</p>
</div>
</div>
<script>
function doSomething(obj, evt) {
alert(obj.id); // 先彈出 child2
var e = evt || window.event;
// 阻止冒泡
if (e.stopPropagation) {
e.stopPropagation(); // 標準瀏覽器
} else {
e.cancelBubble = true; // IE 8-
}
// 注意:這裡不調用 preventDefault,因為 div 無默認行為
}
</script>
點擊 `child2` 時:
document.oncontextmenu = function(e) {
e.preventDefault(); // 阻止瀏覽器默認右鍵菜單
showCustomMenu(e.clientX, e.clientY); // 顯示自定義菜單
};
form.onsubmit = function(e) {
if (!validate()) {
e.preventDefault(); // 驗證失敗,阻止提交
}
};
$('#list').on('click', '.item', function(e) {
// 只處理 .item 的點擊,不想讓外層容器的 click 也觸發
e.stopPropagation();
// 但注意:這會阻斷冒泡到 #list 之上的所有祖先
doSomethingWith(this);
});
// jQuery 事件對象已統一兼容
$('a.external').on('click', function(e) {
e.preventDefault(); // 阻止跳轉
window.open(this.href, '_blank'); // 新標籤打開
});
$('.dropdown-menu').on('click', function(e) {
e.stopPropagation(); // 點擊菜單內部不關閉菜單(冒泡到 document 的關閉邏輯)
});