javascript - 如何使用 attachEvent 引用调用者对象 ("this")

标签 javascript internet-explorer dom 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"
   }
}

我只是编写了这段代码,它与我的代码完全不一样,但如果它适用于它,那么它也适用于我!

最佳答案

来自 this quirksmode article关于 attachEvent:

  1. Events always bubble, no capturing possibility.
  2. The event handling function is referenced, not copied, so the this keyword always refers to the window and is completely useless.

The result of these two weaknesses is that when an event bubbles up it is impossible to know which HTML element currently handles the event. I explain this problem more fully on the Event order page.

Since the Microsoft event adding model is only supported by Explorer 5 and higher on Windows, it cannot be used for cross–browser scripts. But even for Explorer–on–Windows only applications it’s best not to use it, since the bubbling problem can be quite nasty in complex applications.

我还没有测试过,但一个可能的解决方法是将处理程序包装在一个匿名函数中,该函数通过 funct.call() 调用您的处理程序。

else if(element.attachEvent){
   element.attachEvent("on"+name, function(){ funct.call( element ) });
}

对于未经测试的解决方案,我深表歉意。我不喜欢这样做,但现在无法轻松访问 IE。

关于javascript - 如何使用 attachEvent 引用调用者对象 ("this"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4590122/

相关文章:

javascript - 在另一个字段中显示html表单的输入值

html - 为什么它的 bordercolour 似乎只在 chrome 而不是 internet explore 或 firefox 中运行

javascript - 检测 DOM 元素顺序的变化

javascript - Chrome 扩展 : sendMessage from content to background getting response from popup

javascript - 将 Jquery 脚本与 AJAX 相结合

javascript - 在 Javascript : Change of pattern 中从经典继承切换到原型(prototype)继承

JavaScript:如何在 Internet Explorer 中模拟更改事件(委托(delegate))

html - 粘性页脚奇怪的 IE11 行为

javascript - 如何在黑莓浏览器上动态添加脚本元素?

javascript - 使用 jQuery 获取 DOM 元素的 XPath