一分钟了解如何解决事件冒泡

冒泡事件就是点击子节点,会向上触发父节点,祖先节点的点击事件。我们在平时的开发过程中,肯定会遇到在一个div(这个div可以是元素)包裹一个div的情况,但是呢,在这两个div上都添加了事件,如果点击里面的div我们希望处理这个div的事件,但是呢,我们不希望外层的div的事件也执行,这时候我们就要用到阻止冒泡。

通俗点来说吧,你在家里看电视,躲在自己的小房间,但是你不希望声音传到隔壁父母的耳朵里,这时候,你可能躲在被窝里,或者墙壁的隔音效果很好,阻隔声音可以理解为阻止冒泡。

<style>
	        #content{
	            width: 140px;
	            border: 1px solid blue;
	            text-align: center;
	        }
	        #msg{
	            width: 100px;
	            height: 100px;
	            margin: 20px;
	            border: 1px solid red;
	        }
</style>

<body>
<div id="content">
   外层div
<div id="msg">
    内层div
 </div>
</div>

 

  $(function(){   //阻止事件冒泡前
        // 为内层div绑定click事件
        $("#msg").click(function(){
            alert("我是小div");
        });
     // 为外层div元素绑定click事件
        $("#content").click(function(){
            alert("我是大div");
        });
        // 为body元素绑定click事件
        $("body").click(function(){
            alert("我是body");
        });
    });
    $(function(){   //阻止事件冒泡后 
        // 为内层div绑定click事件
        $("#msg").click(function(event){
            alert("我是小div");
            event.stopPropagation();    //  阻止事件冒泡
        });
     // 为外层div元素绑定click事件
        $("#content").click(function(event){
            alert("我是大div");
            event.stopPropagation();    //  阻止事件冒泡
        });
        // 为body元素绑定click事件
        $("body").click(function(event){
            alert("我是body");
            event.stopPropagation();    //  阻止事件冒泡
        });
    });

 

posted @ 2017-01-04 11:17  学无止境的小学生  阅读(1420)  评论(0编辑  收藏  举报