• 事件冒泡与阻止事件冒泡


    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <script type="text/javascript" src="js/jquery1.42.min.js"></script>
            <script type="text/javascript" src="js/jquery.SuperSlide.2.1.1.js"></script>
            <style>
                .pic{1000px;margin:50px auto;}            
                .pic li{list-style: none;float: left;200px;margin-right: 20px;}
                .pic li img{ 100%;}
                .posi{display:none;500px;position: absolute;top:50px;left:318px;}        
            </style>
        </head>
        <body>
            <div id="content" style="200px;height: 200px;background: #ccc;">
                外层div
                <span style="text-indent: 2em;display: block;background: red;">内层span元素</span>
                外层div元素
            </div>
            <div id="msg" style="padding-bottom: 200px;"></div>
            <script type="text/javascript">
                $(function(){
                    //为span元素绑定click事件
                    $('span').bind('click',function(event){
                        var txt =$('#msg').html()+'<p>内层span元素被点击.</p>';
                        $('#msg').html(txt);
                        event.stopPropagation();
                        
                    });
                    //为div绑定click事件
                    $('#content').bind('click',function(event){
                        var txt=$('#msg').html()+'<p>外层div元素被点击.</p>';
                        $('#msg').html(txt);    
                        event.stopPropagation();
                        
                    });
                    //为body事件绑定click事件
                    $('body').bind('click',function(){
                        var txt =$('#msg').html()+'<p>body元素被点击.</p>';
                        $('#msg').html(txt);
                    })
                })
            </script>
        </body>
    </html>
    //    浏览器兼容性问题

    使用jQuery给一个事件加处理方法时,为了阻止一个事件向上冒泡,使用了event.stopPropagation(),但在IE下却报对象不支持此属性或方法的错误(IE下是event. cancelBubble=true),jquery不是兼容各浏览器吗?

    后来看了下jQuery的官方文档后,原来在使用event的时候,必须在事件处理方法中加入参数event,否则这个event为 window.event,而不是jQuery中的event。所以在jQuery定义事件处理方法时,最好加上参数event,如下:

    1. $('#btn').click(function(event){})  //推荐  
    2. $('#btn').click(function(){})  //不推荐  
     
  • 相关阅读:
    Android OCR 之 tesseract
    抛砖引玉 之 谁动了我的流量(0权限上传数据)
    退伍一年了
    android 通过 Hessian 与 j2ee 服务端交互
    Arduino 入手
    抛砖引玉 之 谁动了我的隐私(android用户隐私窥探)
    如何关注那些有价值的微博
    关于培训和外包20111027
    ASP.NET实现Cookie功能的三个基本操作(写入,读取,删除)
    提高你开发效率的十五个Visual Studio 2010使用技巧
  • 原文地址:https://www.cnblogs.com/wangmeiMeo/p/7207128.html
Copyright © 2020-2023  润新知