JavaScript 中的 window.event 是什么?

mfa*_*ghi 3 javascript events

我只是无法理解window.event()JavaScript 中的内容。它在没有任何定义的情况下使用。同样的事情document.event()。我也不明白这两者的区别。他们接受任何论据吗?

Can*_*vas 6

事件是在发生某些事情时调用的东西,因此例如单击和按键是事件。

然而,原因window.event()是为了跨浏览器兼容性。所以这里有一些 javascript:

object.onclick = function(e) {
  // e holds all of the properties of the event
  // You can access the event properties like so e.target
}
Run Code Online (Sandbox Code Playgroud)

但是,Internet Explorer 不像其他浏览器那样处理 JavaScript。因此,为了让 Internet Explorer 处理与上述相同的代码,我们将在以下行中编写一些内容

object.onclick = function() {
  alert(window.event.srcElement); // Same as e.target
}
Run Code Online (Sandbox Code Playgroud)

或者您可以将它们组合在一起,如下所示:

object.onclick = function(e) {
  e = e || window.event; // Use e if it exists or e will be equal to window.event
  var target = e.target || e.srcElement; // We then use the e.target property but if that doesn't exist we use e.srcElement
  alert(target);
}
Run Code Online (Sandbox Code Playgroud)

  • *“然而,window.event() 的原因是为了兼容跨浏览器”* 嗯没有。IE 的处理方式与其他浏览器不同,这就是我们拥有它的原因。另请注意,OP 正在谈论“window.event()”,而不是“window.event”。 (3认同)