JS通用事件绑定和移除程序

 

首先判断是否可使用DOM2级方法,然后判断是否可使用IE方法,最后只能使用DOM0级方法

 

  <script type="text/javascript">
  var EventUtil = {
    addhandler: function(element, type, handler){
      if (element.addEventListener) {
        element.addEventListener(type, handler, false);
      } else if (element.attachEvent) {
        element.attachEvent("on" + type, handler);
      } else {
        elemnet["on" + type] = handler;
      }
    },
    removeHandler: function(){
      if (element.addEventListener) {
        element.removeEventListener(type, handler, false);
      } else if (element.attachEvent) {
        element.detachEvent("on" + type, handler);
      } else {
        elemnet["on" + type] = null;
      }
    
    }
  };
  </script>

 

2014-05-08 追加

学习thc1987的代码,改进如下(其实是原封不动抄过来的)

addEvent : function(oTarget,sEventType,fn){
		if(oTarget.addEventListener){
			this.addEvent = function(oTarget,sEventType,fn) {
				oTarget.addEventListener(sEventType,fn,false);
			}
		}else if(oTarget.attachEvent){
			this.addEvent = function(oTarget,sEventType,fn) {
				oTarget.attachEvent("on" + sEventType,fn);
			}
		}else{
			this.addEvent = function(oTarget,sEventType,fn) {
				oTarget["on" + sEventType] = fn;
			}
		}
		// 调用新函数
		this.addEvent(oTarget,sEventType,fn);
	}

 

你可能感兴趣的:(js)