js中addachEvent,addEventListener的使用方法

代码

//js中addachEvent,addEventListener的使用方法
//非IE浏览器的动态添加,注销事件的方法
el.addEventListener('click', msg, false);//添加
el.removeEventListener('click', msg, false);//注销
//IE中动态添加事件的方法
el.attachEvent('onclick',msg);//添加
el.detachEvent('onclick',msg);//注销
例:
<body>
<input id="123" type="text" id="test" value="点击" />
<input id="Button1" type="button" onclick="ok()" value="删除动态添加的事件" />
<script>
var el
= document.getElementById("123"); //先取得对象
alert("el.addEventListener=="+el.addEventListener);//提示
alert("el.attachEvent=="+el.attachEvent);
if (el.addEventListener) //用于 Mozilla系列
{
el.addEventListener(
'click', msg, false);
}
else if (el.attachEvent) //非Mozilla系列(IE)
{
el.attachEvent(
'onclick', msg);
}
if (window.addEventListener) //
{
window.addEventListener(
'load',msg, false);
}
else if (window.attachEvent)
{
window.attachEvent(
'onload', msg);
}
function msg()
{
alert(
"我是动态添加的");
}
function ok()
{
if (el.removeEventListener) //用于 Mozilla系列
{
el.removeEventListener(
'click', msg, false);
}
else if (el.detachEvent) //IE中动态添加事件的方法
{
el.detachEvent(
'onclick', msg);
}
}
</script>
</body>

 

posted @ 2010-12-14 18:26  kelin418  阅读(806)  评论(0编辑  收藏  举报