原生js中return false不能阻止事件冒泡,只能阻止默认行为,jquery中return false都可以阻止

2017-11-23 15:24:40 3,945 views

js中
 

<!DOCTYPE html>
<html lang="zh">
  <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>
  </head>
  <body>
    <button>点击</button>
    <a href="##" target="_blank">跳到新的空白页</a>
    <script type="text/javascript">
      var a=document.getElementsByTagName("a")[0];
      var btn = document.getElementsByTagName("button")[0];
      a.onclick=function(){
        return false;//阻止a的默认行为
      }
      btn.onclick = function() {
        alert(1);
        return false;
      }
      document.body.onclick = function() {
        alert(1);
      }
    </script>
  </body>
</html>

 
//弹出了2次警告框输出1
 
jquery中
 

<!DOCTYPE html>
<html lang="zh">
  <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>
  </head>
  <body>
    <button>点击</button>
    <a href="##" target="_blank">跳到新的空白页</a>
    <script src="http://code.jquery.com/jquery-1.11.3.js"></script>
    <script type="text/javascript">
      $(function() {
        $("a").click(function(){
          return false;//阻止默认行为
        });
        $("button").click(function() {
          alert(1);
          return false;//阻止默认行为和冒泡
        });
        $(document).click(function() {
          alert(1);
        });
      })
    </script>
  </body>
</html>

 
//结果只有一次警告框输出1
 

0

分享到微信朋友圈

打开微信,点击底部的“发现”,
使用“扫一扫”即可将网页分享至朋友圈。