以下在 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>
.attachEvent()
不给你this
作为元素。您需要将处理程序包装在一个函数中,该函数从它所附加的元素的上下文中调用它。
if( this.element.attachEvent ) {
var that = this;
this.element.attachEvent("onclick", function() {
that.handleEvent.call( that.element );
} );
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)