DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 關於js注冊事件的常用方法
關於js注冊事件的常用方法
編輯:關於JavaScript     

不解釋,看代碼:

復制代碼 代碼如下:
;(function(){
    //進行庫封裝,防止對象污染
    window['cm']={};
/**
    *給對象注冊事件
    */
    var addListener=function(element,type,fn){
        if(typeof element == 'undefined') return false;
        if(element.addEventListener){
            element.addEventListener(type,fn,false);
        }else if(element.attachEvent){
            //將事件緩沖到該標簽上,已解決this指向window(現fn內this指向element)和移除匿名事件問題
            var _EventRef='_'+type+'EventRef';
            if(!element[_EventRef]){
                element[_EventRef]=[];
            }
            var _EventRefs=element[_EventRef];
            var index;
            for(index in _EventRefs){
                if(_EventRefs[index]['realFn']==fn){
                    return;
                }
            }
            var nestFn=function(){
                fn.apply(element,arguments);
            };
            element[_EventRef].push({'realFn':fn,'nestFn':nestFn});
            element.attachEvent('on'+type,nestFn);
        }else{
            element['on'+type]=fn;
        }
    };
    window['cm']['addListener']=addListener;
    /**
    *移除對象上已注冊事件
    */
    var removeListener=function(element,type,fn){
        if(typeof element == 'undefined') return false;
        if(element.removeEventListener){
            element.removeEventListener(type,fn,false);
        }else if(element.detachEvent){
            var _EventRef='_'+type+'EventRef';
            if(!element[_EventRef]){
                element[_EventRef]=[];
            }
            var _EventRefs=element[_EventRef]
            var index;
            var nestFn;
            for(index in _EventRefs){
                if(_EventRefs[index]['realFn']==fn){
                    nestFn=_EventRefs[index]['nestFn'];
                    if(index==_EventRefs.length-1){
                        element[_EventRef]=_EventRefs.slice(0,index);
                    }else{
                        element[_EventRef]=_EventRefs.slice(0,index).concat(_EventRefs.slice(index+1,_EventRefs.length-1));
                    }
                    break;
                }
            }
            if(nestFn){
                element.detachEvent('on'+type,nestFn);
            }
        }else{
            element['on'+type]=null;
        }
    };
})();

 

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved