javascript 事件对象不仅仅在 Firefox 中定义(IE 和 Chrome 都可以使用)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25775587/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:59:59  来源:igfitidea点击:

event object not defined only with Firefox (IE and Chrome works)

javascripthtmlinternet-explorergoogle-chromefirefox

提问by Luca

<a class="lnk" href="#" onclick="showItem();">
    <span data-id="27">TEST</span>
</a>

function showItem()
{
    var itid = event.target.dataset.id;
    alert(itid);
}

If you try this jsfiddle codeyou can see that with IE (11) and Chrome the event object is correctly evaluated, but with Firefox (32.0) you get an error (ReferenceError : event is not defined)

如果您尝试使用此 jsfiddle 代码,您可以看到使用 IE (11) 和 Chrome 正确评估了事件对象,但使用 Firefox (32.0) 会出现错误(ReferenceError : event is not defined)

It's a bug of Firefox or a different event object lifecycle in IE and Chrome ? However since in IE and Chrome it's working I think it's a problem. About a workaround ?

这是 Firefox 的错误还是 IE 和 Chrome 中的不同事件对象生命周期?然而,由于在 IE 和 Chrome 中它正在工作,我认为这是一个问题。关于解决方法?

p.s: in jsfiddle, only with firefox, code selection still having problem (after some run you cannot select code.

ps:在jsfiddle中,只有firefox,代码选择仍然有问题(运行一段时间后,你无法选择代码。

回答by Barmar

You should pass eventas an argument to the function:

您应该event作为参数传递给函数:

<a class="lnk" href="#" onclick="showItem(event);">
    <span data-id="27">TEST</span>
</a>

function showItem(e)
{
    e = e || window.event;
    var itid = e.target.dataset.id;
    alert(itid);
}

Accessing it as a global variable is an IE feature that Chrome copied, but I don't think it's standard Javascript.

将其作为全局变量访问是 Chrome 复制的 IE 功能,但我认为它不是标准的 Javascript。