zoukankan      html  css  js  c++  java
  • event.stopPropagation()与event.preventDefault()

    <div id='div0'>
      <div id='div1'>
        <a href="#" id='div2'>2222</a>
      </div>
    </div>

    window.onload=function(){
        var div0=document.getElementById('div0');
        var div1=document.getElementById('div1');
        var div2=document.getElementById('div2');
        div0.onclick=function(e){
            alert('00');
        }
        div1.onclick=function(e){
            alert('11');
        }
        div2.onclick=function(e){
            alert('22');
        }
    
    }   // 点击22222后,以次弹出22,11,00(事件冒泡)

    (1)event.preventDefault()表示阻止默认事件发生:如a标签的跳转事件

    我们给a标签添加该事件,则a不再跳转。

     div0.onclick=function(e){
            alert('11');
            e.preventDefault();
      }

    (2)event.stopPropagation() 表示阻止冒泡事件发生:冒泡指的是向上层冒泡,不影响他的子元素

    例如:我们给div1 添加阻止冒泡事件,div2依然会触发,但是div0不会。

     div1.onclick=function(e){
            alert('11');
            e.stopPropagation();
      }
    // 依次弹出 22, 11


            







  • 相关阅读:
    (转载)关于一些对location认识的误区
    Python内置数据结构--列表
    Maven
    Python基础语法
    安装ipython和jupyter
    Python环境安装
    Java多线程
    SpringMVC集成springfox-swagger2自动生成接口文档
    SpringMVC拦截器
    SpringMVC异常处理器
  • 原文地址:https://www.cnblogs.com/telnetzhang/p/5858044.html
Copyright © 2011-2022 走看看