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 好粗心

  • 相关阅读:
    java 中的锁 -- 偏向锁、轻量级锁、自旋锁、重量级锁(转)
    MySQL存储引擎--MyISAM与InnoDB区别
    Socket详解
    Java线程池参数
    Java反射机制(转)
    java注解
    docker入门实例
    docker常用命令总结
    showdoc 自动脚本安装
    [mysql]You must reset your password using ALTER USER statement before executing this statement.
  • 原文地址:https://www.cnblogs.com/chuyu/p/3502322.html
Copyright © 2011-2022 走看看