日期:2014-05-16  浏览次数:20332 次

有接触过设计模式一书中的addEvent的吗,为什么this.id在ie下显示不出元素id啊?
代码如下:
<div id="div1" style="background:yellow; height:100px; width:100px"></div>



var box=document.getElementById('div1');
function addEvent(el,type,fn){  
if(window.addEventListener) {
el.addEventListener(type,fn,false);
}
else if(window.attachEvent)  {
el.attachEvent('on'+type,fn);
}
else{
el['on'+type]=fn;
}   
}

addEvent(box,'click',f1);
addEvent(box,'click',f2);

function f1(){
   alert('here')
   alert(this.id)
   alert(this)
}

function f2(){
   alert('there')
   alert(this.id)
   alert(this)
}



------解决方案--------------------
改一下吧。

function addEvent(el,type,fn){  
    if(window.addEventListener) {
        el.addEventListener(type,fn,false);
    }
    else if(window.attachEvent)  {
        el.attachEvent('on'+type,function(){
              fn.call(el);
        });
    }
    else{
        el['on'+type]=fn;
    }   
}


这里的this本来是指向window,原理不太明白。。