• 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>

     

  • 相关阅读:
    python list介绍
    python unittest模块
    python 贪婪算法
    python 动态规划:背包问题
    汇编语言 基础知识(王爽)
    python 迪克斯特拉(Dijkstra)
    python 广度优先查找 (最短路径)
    Python 快速排序
    python 分而治之 找零数量 最小组合
    移动端的头部标签和 meta
  • 原文地址:https://www.cnblogs.com/MelodysBlog/p/10584105.html
Copyright © 2020-2023  润新知