JS 动态注册事件

JS当中动态注册事件,可以有好几种方式,但兼容性最好的是以下的方式:

 

//elementid:要注册事件的HTML控件的ID

//type:注册事件的名称,(例如:blur focus focusin focusout load resize scroll unload click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup error)

//eventHandle:事件的回调函数

var RegEvent=function(elementid, type,eventHandle)
{
    var elem=document.getElementById(elementid);    
           
    if ( elem.addEventListener ) { //firefox下用这个
        elem.addEventListener( type, eventHandle, false );

    } else if ( elem.attachEvent ) { //ie下用这个
         elem.attachEvent( "on" + type, eventHandle );
    }
}

-----------------------------

下面写一个相当简单的例子

<html>

<head>
<script>
var RegEvent=function(elementid, type,eventHandle)
{
    var elem=document.getElementById(elementid);    
           
    if ( elem.addEventListener ) {
	    elem.addEventListener( type, eventHandle, false );

    } else if ( elem.attachEvent ) {
	     elem.attachEvent( "on" + type, eventHandle );
    }
}


function init(){	
    	RegEvent("btn1","click", function(){
    		    alert("please input you name");
    		}
    	);
        //是可以注册多次的
	RegEvent("btn1","click", function(){
    		    alert("please input you name again!");
                   //使用  this.event.srcElement 就可以拿到 btn1的这个对象
} ); } //页面导入后注册事件 window.onload=function(){ init(); //调用init()函数 } </script> </head> <body> <input type="button" value="Please click me" id="btn1"/> </body> </html>

 

 

 

 

 

你可能感兴趣的:(JS 动态注册事件)