zoukankan      html  css  js  c++  java
  • 事件冒泡、组织事件冒泡、以及组织默认行为

    1、事件冒泡

    当事件发生后,这个事件就要开始传播(从里到外或者从外向里)。为什么要传播呢?因为事件源本身(可能)并没有处理事件的能力,即处理事件的函数(方法)并未绑定在该事件源上。例如我们点击一个按钮时,就会产生一个click事件,但这个按钮本身可能不能处理这个事件,事件必须从这个按钮传播出去,从而到达能够处理这个事件的代码中(例如我们给按钮的onclick属性赋一个函数的名字,就是让这个函数去处理该按钮的click事件),或者按钮的父级绑定有事件函数,当该点击事件发生在按钮上,按钮本身并无处理事件函数,则传播到父级去处理。

    <!DOCTYPE html>
    <html lang="en" onclick="alert('html')">
    <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">
        <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
        <title>Document</title>
    </head>
    <body onclick="alert('body')">
        <!--html-->
        <div style="400px; height:400px; background:red" onclick="alert(this.style.background)">
                <div id="div2" style="300px; height:300px; background:palevioletred">
                        <div style="200px; height:200px; background:yellow" onclick="alert(this.style.background)">
                                <div id="div1" style="100px; height:100px; background:palegreen">
                                    <a id="aaa" href="http://www.baidu.com">aaa</a> 
                                </div>
                        </div>
                </div>
        </div>
    
        <script>
            //此jquery既阻止默认行为又停止冒泡
            // $("#div1").on('click',function(){
            //     return false;
            // });
    
            window.onload = function () {
                var oDiv1 = document.getElementById('div1');
                var oDiv2 = document.getElementById('div2');
    
                oDiv1.onclick = function (ev){
                    var oEvent = ev || event;
                    alert("this is div1");
                    
                    //js阻止事件冒泡
                    //oEvent.cancelBubble = true;
                    //oEvent.stopPropagation();
    
                    //js阻止链接默认行为,没有停止冒泡
                    //oEvent.preventDefault(); 
                    //return false;
                }
    
                oDiv2.onclick = function (ev){
                    var oEvent = ev || event;
                    alert("this is div2");
                    oEvent.cancelBubble = true; 
                }
            }
        </script>
    </body>
    </html>
    

  • 相关阅读:
    how to pass a Javabean to server In Model2 architecture.
    What is the Web Appliation Archive, abbreviation is "WAR"
    Understaning Javascript OO
    Genetic Fraud
    poj 3211 Washing Clothes
    poj 2385 Apple Catching
    Magic Star
    关于memset的用法几点
    c++ 函数
    zoj 2972 Hurdles of 110m
  • 原文地址:https://www.cnblogs.com/lml-lml/p/10167533.html
Copyright © 2011-2022 走看看