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 ElementById(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 ElementById(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");
}
)
;
//是可以注册多次的
blur事件RegEvent("btn1","click", function(){
alert("please input you name again!");
//使⽤  this.event.srcElement 就可以拿到 btn1的这个对象
}
);
}
//页⾯导⼊后注册事件
init(); //调⽤init()函数
}
</script>
</head>
<body>
<input type="button" value="Please click me" id="btn1"/>
</body>
</html>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。