js事件冒泡--通俗易懂

①父元素的事件阻止子元素触发,父元素绑定完事件后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(),该子元素才不会受父元素的事件影响

猜你喜欢

转载自blog.csdn.net/weixin_43939111/article/details/111862899