js event bubbling-easy to understand

①The event of the parent element prevents the child element from triggering, and the parent element binds the event to return false.
②The child element event prevents the parent element from triggering, and the child element needs to add stopPropagation().
The following is a small case written by myself

<!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>

I used to be stupid thinking that the parent element will prevent events from grandchildren, great-grandchildren, but in the parent element, the child element takes the initiative e.stopPropagation(), so that the child element will not be affected by the event of the parent element.

Guess you like

Origin blog.csdn.net/weixin_43939111/article/details/111862899