zoukankan      html  css  js  c++  java
  • 复习事件委托

    Css:

    #click-wrap{width: 900px;height: 30px;background: #fc0;}
    button{display: inline-block;width: 180px;height: 30px;line-height: 30px;text-align: left;padding: 0 20px;cursor: pointer;}

    HTML :

      <div id="click-wrap">
            <button>click me: 0 </button>
            <button>click me too: 0 </button>
            <button>click me three: 0 </button>
        </div>

    JS :

      var wrap = document.getElementById("click-wrap");
    
        function addEvent(el, type, fn){
            if(document.body.addEventListener){
                addEvent = function(el, type, fn){
                    console.log(00)
                    el.addEventListener(type, fn, false);
                };
            }else{
                addEvent = function(el, type, fn){
                    el.attachEvent("on" + type, function(){
                        fn.apply(el, arguments);
                    });
                };
            }
            addEvent(el, type, fn);
        };
    
        function myHandler(e){
            console.log(11)
    
            var src, parts;
    
            // 获取事件和源元素
            e = e || window.event;
            src = e.target || e.srcElement;
    
            if(src.nodeName.toLowerCase() !== "button"){
                return;
            }
    
            // 实际工作:升级标签
            parts = src.innerHTML.split(": ");
            parts[1] = parseInt(parts[1], 10) + 1;
            src.innerHTML = parts[0] + ": " + parts[1];
    
            // 无冒泡
            if(typeof e.stopPropagation === "function"){
                e.stopPropagation();
            }
            if(typeof e.cancelBubble !== "undefined"){
                e.cancelBubble = true;            
            }
    
            // 阻止默认操作
            if(typeof e.preventDefault === "function"){
                e.preventDefault();
            }
            if(typeof e.returnValue !== "undefined"){
                e.returnValue = false;
            }
        }
    
        addEvent(wrap, "click", myHandler);

     再次复习了事件委托,addEvent先写好了,也知道原理,但有个if else 我就直接写的return 导致后面的语句addEvent(el, type, fn)没有执行 0.0 好粗心

  • 相关阅读:
    springboot雷神更新
    JVM整理文档
    这是我见过BIO/NIO/AIO讲的最清楚的博客了
    redis主从机制
    mybatis是如何防止sql注入的
    分布式锁的实现方式简介
    Nginx简介
    .net 下的集合
    C#模拟百度登录
    WPF 将PPT,Word转成图片
  • 原文地址:https://www.cnblogs.com/chuyu/p/3502322.html
Copyright © 2011-2022 走看看