JavaScript 动态平添事件 和 获取Event (兼容IE和Firefox)

JavaScript 动态添加事件 和 获取Event (兼容IE和Firefox)

 

1、直接给对象添加事件
document.all.Object.ondblclick=function(){方法};

2、通过监听方式添加事件,多事件可并存,按添加顺序执行。
if(window.addEventListener)
    // Mozilla, Netscape, Firefox
    Object.addEventListener("click", function(){方法}, false);
else if(window.attachEvent)
    // IE
    Object.attachEvent("onclick", function(){方法});

else
    // Other

    Object.onclick= function(){方法};

例子:

 

function srchtxtAddOnKeyPress()
{
    if(window.addEventListener)
    { 
        //其它浏览器的事件代码: Mozilla, Netscape, Firefox
        //添加的事件的顺序即执行顺序 //注意用 addEventListener 添加带on的事件,不用加on 
        document.getElementById('srchtxt').addEventListener('keypress', keyPressEvt, false);
    }
    else
       {
         //IE 的事件代码 在原先事件上添加 add 方法
          document.getElementById('srchtxt').attachEvent('onkeypress',keyPressEvt);
      }
}

 

3、获取Event

 

//判斷當事件keyCode值為13時觸發登錄事件
	userLoginPasd.onkeydown = function(e){
		var e = e || window.event;
		if(e.keyCode == 13){
			login();
		} 
	}
 

 

 下面提供同时兼容IE和Firefox的获得event对象的方法,在需要用到event对象的地方,调用该方法即可.

function getEvent() //同时兼容ie和ff的写法
    { 
        if(document.all)  return window.event;   
        func=getEvent.caller;       
        while(func!=null){ 
            var arg0=func.arguments[0];
            if(arg0)
            {
              if((arg0.constructor==Event || arg0.constructor ==MouseEvent) || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation))
              { 
              return arg0;
              }
            }
            func=func.caller;
        }
        return null;
    } //如调用:
document.onclick=function(){

var evt=getEvent();
alert(evt);
}