Javascript";这";在IE中失去语境

Javascript";这";在IE中失去语境,javascript,prototype,this,Javascript,Prototype,This,以下内容在firefox/safari/chrome中运行良好,在IE中,handleEvent()函数中的“this”似乎正在丢失上下文……警报的结果是[object Window],这不是我想要的;从handleEvent()输出时,“this”需要是对HandleClick对象的引用,而不是对Window对象的引用 我是不是遗漏了一些基本的东西导致IE出现这种情况 <html> <head> <script type="text/javascript">

以下内容在firefox/safari/chrome中运行良好,在IE中,handleEvent()函数中的“this”似乎正在丢失上下文……警报的结果是[object Window],这不是我想要的;从handleEvent()输出时,“this”需要是对HandleClick对象的引用,而不是对Window对象的引用

我是不是遗漏了一些基本的东西导致IE出现这种情况

<html>
<head>
<script type="text/javascript">
HandleClick = function(el) {
    this.element = document.getElementById(el);
    if( this.element.addEventListener ) {
        this.element.addEventListener("click", this, false);
    } else {
        if( this.element.attachEvent ) {
            this.element.attachEvent("onclick", this.handleEvent);
        }
    }
}
HandleClick.prototype = {
    handleEvent: function(e) {
        alert(this);
    }
}
</script>
</head>
<body onload="new HandleClick('logo')"></body>
</html>

HandleClick=功能(el){
this.element=document.getElementById(el);
if(this.element.addEventListener){
this.element.addEventListener(“单击”,this,false);
}否则{
if(this.element.attachEvent){
this.element.attachEvent(“onclick”,this.handleEvent);
}
}
}
HandleClick.prototype={
handleEvent:功能(e){
警惕(这个);
}
}
.attachEvent()
不会将此
作为元素提供给您。您需要将处理程序包装在一个函数中,该函数从它所附加到的元素的上下文中调用它

    if( this.element.attachEvent ) {
        var that = this;
        this.element.attachEvent("onclick", function() { 
                                              that.handleEvent.call( that.element );
                                           } );
    }

很好的第一个问题。欢迎来到SO!我尝试了上面的建议,在这种情况下,.handleEvent.call()似乎并没有像预期的那样工作(在ie中);但是.handleEvent(that.element)确实有效。尽管我可以成功地调用该.handleEvent(),但它似乎没有传递“event”(或“e”)参数。有什么建议吗?@ahallerblu:在IE中对我来说很好。你用的是哪个版本?要在IE中将
事件
对象作为参数传递,需要引用
window.event
。因此,我将调用更改为
that.handleEvent.call(that.element,window.event).call()
,而是想像您那样将元素作为参数传递,那么只需添加
事件
对象即可
that.handleEvent(that.element,window.event)
我正在使用ie8。不管怎样,我不知道我能用window.event这样的东西。由于使用.call没有正确地为我传递第二个参数,我最终执行了.handleEvent(window.event,that)
。@ahallerblu:奇怪的是,
.call()
不起作用。我得做些测试。不管怎样,很高兴你找到了可行的方法。