javaScript事件冒泡

一,什么是事件冒泡?

在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序,如果没有定义此事件处理程序或事件返回true,那么这个事件会向这个对象的的父级传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活),或者到达了对象层次的最顶层,即document对象。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js事件冒泡</title>
</head>
<style>
    .outSide{
        width:100px;
        height:100px;
        background:#000;
        padding:50px;
    }

    .inSide{
        width:100px;
        height:100px;
        background:#CCC
    }

</style>
<body>
<div onclick="outSideWork()" id="outSide" class="outSide">
    <div onclick="inSideWork()" id="inSide" class="inSide">
    </div>
</div>
</body>
    <script type="text/javascript">
        function outSideWork()
        {
            alert('My name is outSide,I was working...');
        }

    function inSideWork()
    {
        alert('My name is inSide,I was working...');
    }
        

</script>
</html>

二,事件冒泡有什么作用?

 (1)事件冒泡允许多个操作被集中处理,(把事件处理器添加到一个父级元素上,避免把事件处理器添加到多个子元素上),它还可以让你在对象层的不同级别捕获事件。

//本例子只在外面盒子定义了处理方法,而这个方法一样可以捕获到子元素点击行为并处理它。假设有成千上万子元素要处理,难道我们要为每个元素加“onclick="eventHandle(event)"”?显然没有这种集中处理的方法来的简单,同时它的性能也是更高的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js事件冒泡</title>
</head>
<style>
    .outSide{
        width:100px;
        height:100px;
        background:#000;
        padding:50px;
    }

    .inSide{
        width:100px;
        height:100px;
        background:#CCC
    }

</style>
<body>
    <div onclick="eventHandle(event)" id="outSide" class="outSide">
        <div id="inSide" class="inSide"></div>
    </div>
</body>
<script>
    function eventHandle(e){
      var e = e||window.event;
      var obj = e.target || e.srcElement;
      alert(obj.id +'was click!')
    }
</script>
</html>

四,阻止事件冒泡

通常情况下我们都是一步到位,明确自己的事件触发源,并不希望浏览器自作聪明、漫无目的地去帮我们找合适的事件处理程序,即我们明确最精准目标,这种情况下我们不需要事件冒泡。事件冒泡处理可能会激活我们本来不想激活的事件,导致程序错乱,所以我们要阻止事件冒泡。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js事件冒泡</title>
</head>
<style>
    .outSide{
        width:100px;
        height:100px;
        background:#000;
        padding:50px;
    }

    .inSide{
        width:100px;
        height:100px;
        background:#CCC
    }

</style>
<body>
<div onclick="showMsg(this,event)" id="outSide" class="outSide">
    <div onclick="showMsg(this,event)" id="inSide" class="inSide">
    </div>
</div>
</body>
<script type="text/javascript">
    function showMsg(obj,e){
        alert(obj.id);
        stopBubble(e)
    }

    //阻止事件冒泡函数
    function stopBubble(e){
        if(e && e.stopPropagation){
            e.stopPropagation()
        }else{
            window.event.cancelBubblr = true
        }
    }
</script>
</html>

 原博链接

原文地址:https://www.cnblogs.com/qianxunpu/p/8041709.html