Javascript事件监听1

本文探讨了在浏览器中使用事件监听(如addEventListener和attachEvent)与直接设置元素事件属性(如onclick)的区别。通过实例展示了事件监听如何支持事件处理程序的并行执行,并讨论了在团队开发中使用事件监听的优势。

firefox中addEventListener()方法和ie中attachEvent()方法都是为HTML元素添加一个事件监听

为什么要采用事件监听而不是直接对元素的事件属性(如:onclick、onmouseover)赋值?

这两种方法处理事件还是有很大区别的!事件属性只能赋值一种方法,即:

button1.onclick = function() { alert(1); };
button1.onclick = function() { alert(2); };
这样后面的赋值语句就将前面的onclick属性覆盖了。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    
<title>Coda Bubble Example</title>
</head>
<body>
<button id="Button1">测试</button>
<script type="text/javascript">
/// <summary>
//
/ 添加事件监听
//
/ </summary>
//
/ <param name="target">载体</param>
//
/ <param name="type">事件类型</param>
//
/ <param name="func">事件函数</param>
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;
}

/// <summary>
//
/ 移除事件监听
//
/ </summary>
//
/ <param name="target">载体</param>
//
/ <param name="type">事件类型</param>
//
/ <param name="func">事件函数</param>
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 Button1Click = function() { alert(1); };
addEventHandler(Button1, 
"click",  Button1Click);
addEventHandler(Button1, 
"click"function() { alert(2); } );
addEventHandler(Button1, 
"click"function() { alert(3); } );

removeEventHandler(Button1, 
"click"function() { alert(2); } ); // 移不出
removeEventHandler(Button1, "click", Button1Click); // 可以移除
</script>
</body>
</html>

而添加事件监听就可以并行。

特别是当团队合作时,事件并行的需求增多,比如:监听document对象的鼠标事件或者window对象的载入事件等。
使用事件属性则很容易造成事件覆盖掉。

经过测试IE(8)中先显示3再显示2,而firefox(3)中则先显示2再显示3
这个是为什么呢?测试的结果即真理,没啥好想的。囧

 

转载于:https://www.cnblogs.com/qiantuwuliang/archive/2009/06/11/1501007.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值