如何使用attachEvent引用调用者对象(“this”)
在IE中使用.attachEvent()
方法,如何用this
引用调用者对象(触发事件的元素)?在普通浏览器中,使用.addEventListener
,var this
指向元素,而在IE中它指向窗口
对象。
我需要它与以下代码一起工作:
var element = //the element, doesn't matter how it is obtained
element.addAnEvent = function(name, funct){
if(element.addEventListener) // Works in NORMAL browsers...
else if(element.attachEvent){
element.attachEvent("on"+name, funct);
//where the value of "this" in funct should point to "element"
}
}
我刚刚编写了该代码,它与我的代码完全不一样,但如果它可以与它一起工作,那么它就可以与我一起工作!
Using the method .attachEvent()
in IE, how can I reference the caller object (the element that triggered the event) with this
? In normal browsers, using .addEventListener
, the var this
points to the element, while in IE it points to the window
object.
I need it to work with the following code:
var element = //the element, doesn't matter how it is obtained
element.addAnEvent = function(name, funct){
if(element.addEventListener) // Works in NORMAL browsers...
else if(element.attachEvent){
element.attachEvent("on"+name, funct);
//where the value of "this" in funct should point to "element"
}
}
I just made that code up, it's not exactly the same as my code, but if it works with it then it works with me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自这篇 quirksmode 文章中关于
attachEvent
的内容:我还没有测试过它,但可能的解决方法是将处理程序包装在一个匿名函数中,该函数通过
funct.call()
调用您的处理程序。对于未经测试的解决方案,我深表歉意。我不喜欢这样做,但现在无法轻松访问 IE。
From this quirksmode article with regard to
attachEvent
:I haven't tested it, but a possible workaround may be to wrap the handler in an anonymous function that calls your handler via
funct.call()
.My apologies for the untested solution. I don't like doing that, but can't easily get to IE right now.
如果您使用的是 IE,则可以通过访问事件处理函数中的
window.event.srcElement
来获取您所称的“调用者”对象。该对象通常称为事件目标或源。该代码未经测试,但应该会让您朝着正确的方向前进。
If you're in IE, you can get the "caller" object, as you call it, by accessing
window.event.srcElement
within the event handler function. This object is normally referred to as the event target or source.This code is untested, but should set you off in the right direction.
绑定它。好吧,您不能使用 javascript 1.8.5 中添加的
Function.prototype.bind
,但您可以使用闭包和Function.prototype.apply
。Bind it. Well, you can't use
Function.prototype.bind
that gets added in javascript 1.8.5, but you can use closure andFunction.prototype.apply
.我认为扩展
Element
对象 会更好, 通过原型链,而不是将您的方法添加到要添加事件的每个元素(适用于所有浏览器)。这样它将适用于您当前的所有 浏览器和未来的元素(并且您只需运行一次)。
I think it would be better to extend the
Element
object , through the prototype chain, instead of adding your method to each element you want to add events to (works with all browsers)..This way it will work for all your current and future elements (and you only have to run it once).