Javascript“这个”在 IE 中丢失上下文
以下在 firefox/safari/chrome 中工作正常,在 IE 中,“this”似乎在 handleEvent() 函数中丢失上下文...警报的结果是 [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>
The following works fine in firefox/safari/chrome, in IE, "this" appears to be losing context in the handleEvent() function...the result of the alert is [object Window], which is not what I want; when output from handleEvent(), "this" needs to be a reference to the HandleClick object, not the Window object.
Am I missing something basic which is causing this in 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.attachEvent()
不会为您提供this
作为元素。您需要将处理程序包装在一个函数中,该函数从它所附加的元素的上下文中调用它。.attachEvent()
doesn't give youthis
as the element. You'd need to wrap the handler in a function that invokes it from the context of the element to which it is attached.