如下
<div id="d1" style="width:200px;height:200px;background:gold;"></div>
<script>
function addEvent(el, type, fn){
if(el.addEventListener){
el.addEventListener(type, fn, false);
}else if(el.attachEvent){
el.attachEvent('on'+type, fn);
}
}
function handler(){
alert("hello");
}
var el = document.getElementById('d1');
addEvent(el, 'click', handler);
addEvent(el, 'click', handler);
</script>
点击黄色背景div
IE6/7/8 :弹出2次hello
IE9/Firefox/Safari/Chrome/Opera :弹1次hello
需要注意的是IE9,它支持标准的addEventListener添加事件,但同时仍然保留了之前IE专有的attachEvent。即IE9中也可以使用attachEvent添加事件。即使如此,使用attachEvent添加事件,在IE9中对于同一个事件handler添加多次,仍然只执行一次。如下
<div id="d1" style="width:200px;height:200px;background:gold;"></div>
<script>
function handler(){
alert('hello');
}
var el = document.getElementById('d1');
el.attachEvent('onclick', handler);
el.attachEvent('onclick', handler);
</script>
如果你正在使用IE6/7/8浏览本文,点击试试