js事件冒泡--通俗易懂
阿新 • • 發佈:2020-12-29
技術標籤:jquery
①父元素的事件阻止子元素觸發,父元素繫結完事件後return false
②子元素事件防止父元素觸發,子元素需新增stopPropagation()
下面是自己寫的小案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<title>Document</title>
<style>
#one{width:400px;height:400px;background-color: red;}
#two{width:200px;height:200px;background-color: green;}
#three{width:50px; height:50px;background-color: blue;}
</style>
</head>
<body>
<div id="one">
一區
<div style="background-color: yellow;width:300px;height:300px;" id="test">子元素群
<div id="two">二區
<div id="three" >三區</div>
</div>
</div>
</div>
<script>
$("#one").click(function(e){
console.log("one")
return false
})
$("#two").click(function(e){
console.log("two")
return false
})
$("#three").click(function(e){
e.stopPropagation()
console.log("three")
})
</script>
</body>
</html>
以前傻乎乎的以為父元素對孫子曾孫子會阻止事件,其實在父元素中,子元素主動e.stopPropagation(),該子元素才不會受父元素的事件影響