关于事件冒泡和浏览器默认行为

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
            #box{
                width: 200px;
                height: 200px;
                background: blue;
            }
    
            #box p{
                width: 100px;
                height: 100px;
                margin: 20px;
                background: green;
            }
    
            #box a{
                color: #fff;
            }
    
            #space{
                height:800px;
                background: #ddd;
            }
        </style>
</head>
<body>
    <div id="space"></div>
    <div id="box">
        <p>hello</p>
        <a href="">add</a>
    </div>
    <script src="lib/jquery-2.2.2.js"></script>
    <script>
        $(document).ready(function(){
            // $('p').click(function(e){
            //     alert('p clicked!')
            //     e.stopPropagation();//阻止事件向上冒泡
            // });
            $('#box').click(function(){
                alert('box clicked!')
            });
            // $('#box a').click(function(e){
            //     $("<input class=''/>").appendTo('#box');
            //     e.stopPropagation();//阻止事件向上冒泡
            //     e.preventDefault();// 阻止浏览器默认行为
            // });
            $('#box a').click(function(e){
                $("<input class=''/>").appendTo('#box');
                return false;// 同时阻止冒泡和默认行为
            });  
     
        });
    </script>
    
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44606660/article/details/88355019
今日推荐