为什么“事件”在Chrome中可用,但不是FF? [英] Why is 'event' available globally in Chrome but not FF?

查看:165
本文介绍了为什么“事件”在Chrome中可用,但不是FF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理另一个问题的答案时,与匿名函数中可用的事件对象相关的奇怪错误没有被传入。在下面的Chrome中工作正常,但FF会引发错误。

While working on an answer for another question, a strange bug came up related to the event object being available in an anonymous function without being passed in. In Chrome the below works fine, but FF throws an error.

$(document).ready(function() {
  $("#uspsSideboxTrackingClose").click(function() {
    event.preventDefault();
    console.log(event);
  });
});

Chrome:

FireFox


ReferenceError:事件未定义

ReferenceError: event is not defined






已经知道


It is already known that

$("#uspsSideboxTrackingClose").click(function(event) { .. }

在两个浏览器中都可以使用。 这里是违规的代码,这是Chrome或FF的错误,还是浏览器的预期行为

works in both browsers. Here is the offending code. Is this a bug with Chrome or FF, or intended behavior by both browsers? Which browser is right?

推荐答案

在IE中,事件对象是一个全局对象,(不传递给处理函数)一个全球对象,你也可以将其作为窗口对象的属性,如 window.event

In IE, the event object was a global object, (which is not passed to the handler function) but accessed as a global object. You can also access it as a property of the window object like window.event

在FF和其他浏览器中,事件对象作为参数传递,因为在FF中没有名为事件的全局属性,您将收到错误消息。

In in FF and other browsers the event object was passed as an argument, since in FF there is no global property called event, you are getting the error message.

在chrome中,它们已经添加了对这两个功能的支持,所以您将获取事件对象作为全局引用和参数。

In chrome they have added support for both these features, so you will get the event object as a global reference and as an argument.

但是,由于您正在使用jQuery ,jQuery将这两个行为标准化,并将始终将事件对象作为参数传递给事件处理程序。

But since you are using jQuery, jQuery normalizes these 2 behaviors and will always pass the event object as an argument to the event handler.

$(document).ready(function () {
    $("#uspsSideboxTrackingClose").click(function (event) {
        event.preventDefault();
        console.log(event);
    });
});

这篇关于为什么“事件”在Chrome中可用,但不是FF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆