JS事件监听器

js事件监听是学习js过程中必然要学习和掌握的。下面是js事件监听的代码
function addEventHandler(target, type, func) {
    if (target.addEventListener)
        target.addEventListener(type, func, false);
    else if (target.attachEvent)
        target.attachEvent("on" + type, func);
    else target["on" + type] = func;
}

有人问我,为什么我要用事件监听呢?因为我在target后面加一个.onclick或者.onmouseover 等等的事

件,各个浏览器都是完全兼容的啊。下面几点就说明我们为什么要使用事件监听器。
第一 :当同一个对象使用.onclick的写法触发多个方法的时候,后一个方法会把前一个方法覆盖掉,也就

是说,在对象的onclick事件发生时,只会执行最后绑定的方法。而是用事件监听则不会有覆盖的现象,

每个绑定的事件都会被执行。但是IE家族先执行后绑定的方法,也就是逆绑定顺序执行方法,其他浏览器

按绑定次数顺序执行方法。

第二 :也是最重要的一点,采用事件监听给对象绑定方法后,可以解除相应的绑定,写法如下
function removeEventHandler(target, type, func) {
    if (target.removeEventListener)
        target.removeEventListener(type, func, false);
    else if (target.detachEvent)
        target.detachEvent("on" + type, func);
    else delete target["on" + type];
}


第三 :解除绑定事件的时候一定要用函数的句柄,把整个函数写上是无法解除绑定的。看实例:
错误的写法:
addEventHandler(Button1, "click", function() { alert("3"); } );
removeEventHandler(Button1, "click", function() { alert("3"); });

正确的写法:
function test(){alert("3");}
addEventHandler(Button1, "click", test );
removeEventHandler(Button1, "click", test);

下面为整个HTML代码示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1.0-Transitional.dtd ">
<html xmlns="http://www.w3.org/1999/xhtml ">
<head>
<title>Javascript事件监听</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<button id="Button1">测试</button>
<script type="text/javascript">
function addEventHandler(target, type, func) {
    if (target.addEventListener)
        target.addEventListener(type, func, false);
    else if (target.attachEvent)
        target.attachEvent("on" + type, func);
    else target["on" + type] = func;
}

function removeEventHandler(target, type, func) {
    if (target.removeEventListener)
        target.removeEventListener(type, func, false);
    else if (target.detachEvent)
        target.detachEvent("on" + type, func);
    else delete target["on" + type];
}

var Button1 = document.getElementById("Button1");
var test1 = function() { alert(1); };
function test2() {alert("2")}
addEventHandler(Button1,"click",test1);
addEventHandler(Button1,"click",test2 );
addEventHandler(Button1,"click", function() { alert("3"); } );
addEventHandler(Button1,"click", function() { alert("4"); } );

removeEventHandler(Button1,"click",test1);
removeEventHandler(Button1,"click",test2);
removeEventHandler(Button1,"click",function() { alert("3"); });
</script>
</body>
</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值