//添加事件函数
//为了解决可读性问题  this传递问题   覆盖问题  而创建下面的函数
function addEvent(obj,type,fn){
    var saved = null;
    if(typeof obj['on'+type] == 'function'){
        saved = obj['on'+type];
    }
    obj['on'+type] = function(){
        if(saved)saved();
        fn.call(this);  //手动传递this 而。onclick可以自动传递this
    }
}

//移除事件函数
function removeEvent(obj,type){
    if(obj['on'+type])obj['on'+type]=null; //解决递归导致的卡死问题  保存过多的上次函数
}//此时会一刀切 把所有保存的函数都移除

addEvent(window,'load',function(){
    var box = document.getElementById('box');
    addEvent(box,'click',toBlue);
});

function toRed(){
    this.className = 'red';
    removeEvent(this,'click');   //递归之前先移除上一次的递归保存的函数
    addEvent(this,'click',toBlue);
}

function toBlue(){
    this.className = 'blue';
    removeEvent(this,'click');
    addEvent(this,'click',toRed);
}

 

posted on 2018-01-25 21:15  YKing_匆  阅读(142)  评论(0)    收藏  举报