zoukankan      html  css  js  c++  java
  • jQuery中return false,e.preventDefault(),e.stopPropagation()的区别

    e.stopPropagation()阻止事件冒泡

    <head>
        <title></title>
        <script src="Scripts/jQuery-1.4.1.js" type="text/JavaScript"></script>
    </head>
    <body>
        <table>
            <tr>
                <td><span>冒泡事件测试</span></td>
            </tr>
        </table>
    </body>

    我们先看这段代码:

        <script type="text/javascript">
            $(function () {
                $("table").click(function () { alert("table alert"); });
                $("td").click(function () { alert("td alert"); });
                $("span").click(function (){
                        alert("span alert");
                });
            });
        </script>

    我们会看到这样的情况:span alert -> td alert -> table alert。这就叫事件冒泡。就是从下到上,从里到外,事件依次触发。

    有的时候我们不希望事件冒泡咋办?

        <script type="text/javascript">
            $(function () {
                $("table").click(function () { alert("table alert"); });
                $("td").click(function () { alert("td alert"); });
                $("span").click(function (e){
                        alert("span alert");      
                        e.stopPropagation();
                });
            });
        </script>

    如果想获得事件相关信息,就要给匿名方法加一个e对象,e就是事件对象。

     

    e.preventDefault()阻止事件默认行为。


    $("a").click(function (e) {
         alert("默认行为被禁止喽");
         e.preventDefault();
    });

    <a href="http://www.baidu.com">测试</a>

     

     

    return false等效于同时调用e.preventDefault()和e.stopPropagation()

     

    return false除了阻止默认行为之外,还会阻止事件冒泡。如果手上有一份jquery源代码的话,可查看其中有如下代码:

    if (ret===false){
      event.preventDefault();
      event.stopPropagation();
    }



  • 相关阅读:
    servlet 与缓存(4)
    向架构师进军---&gt;系统架构设计基础知识
    sql语法:inner join on, left join on, right join on具体用法
    关于sources.list和apt-get [转载]
    SoftReference
    MFC 之 截图工具
    Outlook Express 收发邮件出现&quot;0x800CCC0F&quot;错误代码解决方法
    使用ffmpeg视频编码过程中踩的一个坑
    Libgdx环境搭建及介绍
    从简单的信道预计说起
  • 原文地址:https://www.cnblogs.com/signheart/p/1327c2a805f97b08be6a92f516973ed9.html
Copyright © 2011-2022 走看看