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

    原文链接:https://blog.csdn.net/wxl1555/article/details/53128966

    今天来看看前端的冒泡和事件默认事件如何处理

    1.event.stopPropagation()方法

    这是阻止事件的冒泡方法,不让事件向documen上蔓延,但是默认事件任然会执行,当你掉用这个方法的时候,如果点击一个连接,这个连接仍然会被打开,

    2.event.preventDefault()方法

    这是阻止默认事件的方法,调用此方法是,连接不会被打开,但是会发生冒泡,冒泡会传递到上一层的父元素;

    3.return false  ;

    这个方法比较暴力,他会同事阻止事件冒泡也会阻止默认事件;写上此代码,连接不会被打开,事件也不会传递到上一层的父元素;可以理解为return false就等于同时调用了event.stopPropagation()和event.preventDefault()

    4.我们来看看几组demo,使用jquery进行DOM操作

    //这是html代码,div里面套了一个a标签,连接到百度
    <div class="box1">
    <a href="http://www.baidu.com" target="_blank"></a>
    </div>

    //css代码,a标签占父元素的空间的1/4,背景颜色为红色;
    .box1{
    height: 200px;
    600px;
    margin: 0 auto;
    }
    .box1 a{
    display: block;
    height: 50%;
    50%;
    background:red;
    }

    第一种
    //不阻止事件冒泡和默认事件

    $(".box1").click(function(){
    console.log("1")//不阻止事件冒泡会打印1,页面跳转;
    });


    第二种
    //阻止冒泡
    $(".box1 a").click(function(event){
    event.stopPropagation();//不会打印1,但是页面会跳转;

    });

    $(".box1").click(function(){
    console.log("1")
    });

    第三种
    $(".box1 a").click(function(event){
    //阻止默认事件
    event.preventDefault();//页面不会跳转,但是会打印出1,
    });

    $(".box1").click(function(){
    console.log("1");
    });

    第四种

    $(".box1").click(function(){
    console.log("1")
    });
    //阻止冒泡
    $(".box1 a").click(function(event){
    event.stopPropagation();
    //阻止默认事件
    event.preventDefault() //页面不会跳转,也不会打印出1
    })

    第五种

    $(".box1").click(function(){
    console.log("1")
    });
    $(".box1 a").click(function(event){
    return false;
    //页面不会跳转,也不会打印出1,等于同时调用了event.stopPropagation()和event.preventDefault()

    });

  • 相关阅读:
    ORA00845 MEMORY_TARGET not supported on this system (oracle11g for asianux3 )
    文件处理命令
    网络通信
    Chapter05Usage and Configuration of the Oracle Shared Server
    压缩解压缩命令
    PAT 1088 Rational Arithmetic[模拟分数的加减乘除][难]
    知识点最小二乘学习与正规表达式
    Missing Number[回溯][难]
    PAT 1065 A+B and C[大数运算][溢出]
    PAT 1055 The World's Richest[排序][如何不超时]
  • 原文地址:https://www.cnblogs.com/zyx-blog/p/9337048.html
Copyright © 2011-2022 走看看