Javascript 事件未在 FireFox 中定义,但在 Chrome 和 IE 中可以
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2974601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
event is not defined in FireFox, but ok in Chrome and IE
提问by podeig
I generate HTML using jQuery:
我使用 jQuery 生成 HTML:
$("<a />")
.append("demo")
.click(function () { DemoFunc(event, value.Id) })
This works perfect for Chrome and IE8, but in FireFox I got an error: "event is not defined". I changed the code like this:
这适用于 Chrome 和 IE8,但在 FireFox 中出现错误:“事件未定义”。我改变了这样的代码:
.attr("onclick", "DemoFunc(event, " + value.Id + ")")
It works for Firefox, but not for Chrome and IE.
它适用于 Firefox,但不适用于 Chrome 和 IE。
DemoFunc = function (e, assocGroupId) {
var target = (e.target) ? $(e.target) : $(e.srcElement);
....
}
Why!? Help!!
为什么!?帮助!!
回答by Tim Down
In IE and Chrome, eventis resolving to window.event. Firefox doesn't have this property and instead provides an event to an event handler function by passing it as a parameter. jQuery abstracts this difference for you by providing an event object parameter in all browsers:
在 IE 和 Chrome 中,event解析为window.event. Firefox 没有这个属性,而是通过将事件作为参数传递给事件处理函数来提供事件。jQuery 通过在所有浏览器中提供一个事件对象参数来为您抽象出这种差异:
$("<a />")
.append("demo")
.click(function (evt) { DemoFunc(evt, value.Id) });
回答by Stephen Saucier
If you have structured your code around working with the original event rather than the jQuery event, you can use evt.originalEventto refer to the native event.
如果您围绕使用原始事件而不是 jQuery 事件来构建代码,则可以使用evt.originalEvent来引用本机事件。

