zoukankan      html  css  js  c++  java
  • event.stopPropagation()、event.preventDefault()与return false的区别

    做小demo时经常用到return false来取消默认事件,但一直不是很懂它和preventDefault()等的区别,今天查了查文档和大神们的博客,在这里对相关知识点做一个总结

    首先开门见山,总结一下这三者的区别:

    event.stopPropagation():阻止事件冒泡,对默认事件无影响

    event.preventDefault():阻止默认事件,和事件冒泡无关

    return false:原生js中,阻止默认事件,jQuery中既会阻止默认事件又会阻止事件冒泡

     

    这样理解起来可能不是很清晰,我们都知道,a标签的默认事件之一为点击链接跳转,让我们做一个与此相关的小demo加深一下印象

     

    <!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>
            div{width: 100px;height: 100px;border: 1px solid #ccc;}
            div a{display: block;width: 30px;height: 100px;background: skyblue;}
        </style>
    </head>
    <body>
        <div id="box1">
            <a href="http://www.baidu.com"></a>
        </div>
         <div id="box2">
            <a href="http://www.baidu.com"></a>
        </div>
        <div id="box3">
            <a href="http://www.baidu.com"></a>
        </div>
        <div id="box4">
             <a href="http://www.baidu.com"></a>
        </div>
        <div id="box5">
            <a href="#"></a>
        </div>
        <script>
            /*event.stopPropagation()&&event.preventDefault()&&return false*/
            box1.onclick=function(){
                console.log("parent");        
            }//不阻止默认事件和冒泡,打印并且跳转
    
    /*event.stopPropagtion(),阻止事件冒泡,但不影响默认事件*/ box2.onclick=function(){ console.log("parent"); } box2.children[0].onclick=function(event){ event.stopPropagation();//仅跳转,冒泡被阻止 }

    /*event.preventDefault(),阻止默认事件,但冒泡不被阻止*/ box3.onclick=function(){ console.log("parent"); } box3.children[0].onclick=function(event){ event.preventDefault();//打印parent,不跳转 }

    /*return false; 在原生中,该方法仅会阻止默认事件,相当于调用了event.preventDefault(),但在jQuery中,它 会同时阻止事件冒泡和默认事件*/ box4.onclick=function(){ console.log("parent"); } box4.children[0].onclick=function(){ return false; }</script> </body> </html>

     

  • 相关阅读:
    JUnit报错 java.lang.Exception:No tests found matching
    tomcat配置好后,启动eclipse中的server,不能出现有猫的页面,提示404
    eclipse中的项目无法添加到server下?
    将web应用部署到Tomcat的三种方式
    启动eclipse弹出提示Version 1.7.0_79 of the JVM is not suitable for this product. Version: 1.8 or greater is required怎样解决
    EXISTS 与 NOT EXISTS 的用法及返回结果
    删除具有联合主键的记录
    序列化与反序列化
    tomcat 线程池
    Hibernate的实体类中为什么要继承Serializable?
  • 原文地址:https://www.cnblogs.com/MelodysBlog/p/10584105.html
Copyright © 2011-2022 走看看