防止事件冒泡的三种方式

37 阅读1分钟

示例代码:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>事件冒泡</title>
</head>
    <body>
    <div id="div" onclick="div()">
      <button id="button" onclick="button()">
        <a id="a" href="http://www.baidu.com"mce_href="http://www.baidu.com" onclick="a()">点击我</a>
      </button>
    </div>
    </body>
    <script>
        function div() {
            console.log('我是div!')
        }
        function button() {
            console.log('button!')
        }
        function a() {
            console.log('我是a!')
        }
    </script>
</html>
  1. e.preventDefault(),可以阻止当前标签的默认行为(如示例a标签的跳转),但是并不会阻止事件的冒泡行为(会触发button、div的点击事件)。

    //script标签添加代码
    document.getElementById('a').addEventListener('click',e=>{
        e.preventDefault()
    })
    

    a标签不跳转,输出内容为:

    image.png

  2. e.stopPropagation(),不能阻止当前标签的默认行为(a标签仍然会跳转),但是会阻止事件的冒泡行为(不会触发button、div的点击事件)。

    //script标签添加代码
    document.getElementById('a').addEventListener('click',e=>{
        e.stopPropagation()
    })
    

    a标签跳转,输出内容为:

    image.png

  3. return false,该方法会阻止当前标签的默认行为(a标签不会跳转),且会阻止事件的冒泡行为(不会触发button、div的点击事件),该方法适用于使用jquery的情况,原生js并不支持。

     //引入在线jquery库
     <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
     <script type="text/javascript">
         $('#a').click(e=>{
             return false
         })
         function div() {
             console.log('我是div!')
         }
         function button() {
             console.log('button!')
         }
         function a() {
             console.log('我是a!')
         }
     </script>
    

    a标签不跳转,输出内容为:

    image.png