复习事件委托

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

posted @ 2014-01-02 18:12  楚玉  阅读(238)  评论(1编辑  收藏  举报