为什么事件处理程序在Firefox中引发错误? [英] Why does the event handler throws an error in Firefox?

查看:53
本文介绍了为什么事件处理程序在Firefox中引发错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段在Google Chrome浏览器中可以正常运行,但是如果我在Firefox中运行它,则会抛出错误,提示未定义 event .是什么原因导致这个问题?

The following snippet works fine in the Google Chrome browser, but if I run it in Firefox it throws an error saying event is not defined. What causes this problem?

document.getElementById("btn").addEventListener("click", function() {
  console.log(event.target.id)
});

<input type="button" id="btn" value="Click Me">

推荐答案

全局变量 event 是非标准的,Firefox不支持.

The global variable event is non-standard and Firefox does not support it.

通过标准方法(事件处理程序的第一个参数)访问事件对象.

Access the event object through the standard method (the first argument to the event handler) instead.

document.getElementById("btn").addEventListener("click", function(event) {
  console.log(event.target.id)
});

<input type="button" id="btn" value="Click Me">

这篇关于为什么事件处理程序在Firefox中引发错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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