實際上是事件冒泡的知識點,用更通俗的方式起的標題。
測試頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div onclick="test1(1, event)" style="width:200px;height:200px;border: 1px solid black">
<div onclick="test2(2, event)" style="width:100px;height:100px;border: 1px solid red">
<div onclick="test3(3, event)" style="width:50px;height:50px;border: 1px solid blue">
<a onclick="test4(4, event);" href="Test45.html">aaa</a>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function test1(v, event){
console.log(v);
}
function test2(v, event){
console.log(v);
}
function test3(v, event){
console.log(v);
}
function test4(v, event){
console.log(v);
}
console.log("init");
</script>
</html>
簡單來說,事件的觸發是從內向外的。如果點擊了最內層的a標籤,控制檯會依次輸出4,3,2,1 ,點擊藍色div,會輸出3,2,1。點擊事件會全部觸發,但是有時候我們需要在觸發內層後,不觸發外層事件,這時需要用到stopPropagation函數。
將上述test4改成這樣
function test4(v, event){
console.log(v);
event.stopPropagation();
}
當點擊a標籤後,控制檯只會輸出4 。
event.stopPropagation();
也可以寫成event.cancelBubble = true;
。
順便再介紹另一個方法event.preventDefault();
。它阻止的是事件的默認動作,這個默認動作具體來說就是,a標籤對應的href(跳轉),submit的提交一類的。
舉個例子
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div onclick="test1(1, event)" style="width:200px;height:200px;border: 1px solid black">
<div onclick="test2(2, event)" style="width:100px;height:100px;border: 1px solid red">
<div onclick="test3(3, event)" style="width:50px;height:50px;border: 1px solid blue">
<a onclick="test4(4, event);" href="Test45.html">aaa</a>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function test1(v, event){
console.log(v);
}
function test2(v, event){
console.log(v);
}
function test3(v, event){
console.log(v);
}
function test4(v, event){
console.log(v);
event.stopPropagation();
}
console.log("init");
</script>
</html>
點擊a標籤後,控制檯會打出4,3,2,1,但是不會觸發href="Test45.html"
的跳轉。