冒泡实例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>事件冒泡</title>
<style type="text/css">
#app{
width: 200px;
height: 200px;
border: 1px solid #ff0;
}
</style>
</head>
<body>
<div id="app" onclick="app()">
<button onclick="btn1(event)">btn1</button>
<button onclick="btn2()">btn2</button>
</div>
</body>
<script>
var box=document.getElementsByClassName('box')[0]
function btn1(e){
e.stopPropagation()
console.log("btn1")
}
function btn2(){
console.log("btn2")
}
function app (){
console.log("app")
}
</script>
</html>
btn1按钮 进行了阻止冒泡 点击只触发btn1()事件
btn2按钮 没有进行阻止冒泡 点击之后会触发btn2()和app()事件
<div class="box" onclick="box()">
<div class="app" onclick="app(event)"></div>
</div>
父子div都绑定了click事件
点击子div后父div同时触发click事件,造成事件并发。
阻止JavaScript事件冒泡传递(cancelBubble 、stopPropagation)
function app(e){
//e.stopPropagation()
e.cancelBubble=true;
console.log("app")
}