zoukankan      html  css  js  c++  java
  • JS基础——事件操作总结

    通用事件绑定

     
    function bindEvent(elem,type,fn) {
      elem.addEventListener(type,fn);
    }
    let a =document.getElementById('a');
    bindEvent(a,'click',function(e){
      e.preventDefault() //阻止浏览器默认行为,防止调转
      alert(‘clicked’);
    }) 

    事件冒泡

    <body>
    <div>
    <p id ="p1">激活</p>
    <p id ="p2">取消</p>
    <p id ="p3">取消</p>
    </div>
    <div>
    <p id ="p4">取消</p>
    <p id ="p5">取消</p>
    </div>
    </body>
    let body =document.body
    let p1 =document.getElementById('p1');
    bindEvent(p1,'click',function(e){
        e.stopPropagation(); //阻止事件冒泡
        alert('激活')
    })
    bindEvent(body,'click',function(e){
        alert('取消')
    })

    事件代理 

    <body>
    <div id="div1">
    <p id ="p1">激活</p>
    <p id ="p2">取消</p>
    <p id ="p3">确认</p>
    </div>
    </body>
    
    let body =document.body
    let div1 =document.getElementById('div1');
    bindEvent(div1,'click',function(e){
            const target =e.target;
            if(target.nodeName === 'A') {  //判断是否是a标签
    alert('target.innerHTML')
    }
    }) 

    事件绑定函数(完善)

    function bindEvent(elem,type,selector,fn) {
    if(fn == null){
    fn = selector;
    selector = null;
    }
    elem.addEventListener(type,function(e){
    if(selector){
    const target= e.target
    if(target.matches(seletor)){
    fn.call(target, e)
    }
    }else {
    fn(e);
    }
    });
    }
    

  • 相关阅读:
    强迫症患者
    GG的匹配串
    漂洋过海来看你
    Fire or Retreat
    1011. A+B和C (15)
    1010. 一元多项式求导 (25)
    1009. 说反话 (20)
    1008. 数组元素循环右移问题 (20)
    1007. 素数对猜想 (20)
    1006. 换个格式输出整数 (15)
  • 原文地址:https://www.cnblogs.com/fuGuy/p/9211214.html
Copyright © 2011-2022 走看看