• 复习事件委托


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

  • 相关阅读:
    SpringCloud高可用和高并发
    时间重要性,我们需要如何利用极致
    Spring是什么 包括SpringBean SpringMVC SpringBoot SpringCloud
    Java 线程的基本使用
    JVM 内存模型
    Java 8 ArrayList 详解
    Java 8 HashMap 源码解析
    Docker 运行 MySQL,使用 docker-compose
    Spring Boot 主从读写分离
    Spring Boot 整合 MyBatis 实现乐观锁和悲观锁
  • 原文地址:https://www.cnblogs.com/chuyu/p/3502322.html
Copyright © 2020-2023  润新知