【问题标题】:ReferenceError: event is not defined - FirefoxReferenceError:未定义事件 - Firefox
【发布时间】:2017-04-23 10:34:58
【问题描述】:

我在使用 Firefox(32.0 版)运行此代码时遇到问题

<!DOCTYPE html> 
<html>
  <head>
    <title>Test A</title>

    <script>
      function showCoords(evt){
        alert(
          "clientX value: " + evt.clientX + "\n" +
          "clientY value: " + evt.clientY + "\n"
        );
	}

	function begin(){
	parag = document.getElementById("parag");
	parag.addEventListener("click", function () {showCoords(event); }, false);
      }
    </script>
  </head>
  <body onload = "begin()">
    <p id="parag">To display the mouse coordinates click in this paragraph.</p>
  </body>
</html>

它适用于 Chrome 和其他浏览器,但当我使用 Firefox 32.0 运行它时,它给了我这个错误:

ReferenceError: 事件未定义

相反,这段代码在 Firefox 中运行没有错误:

<!DOCTYPE html> 
<html>
  <head>
    <title>TestB</title>

    <script>
      function showCoords(evt){
        alert(
          "clientX value: " + evt.clientX + "\n" +
          "clientY value: " + evt.clientY + "\n"
        );
      }
    </script>
  </head>
  <body>
    <p onclick="showCoords(event)">To display the mouse coordinates click in this paragraph.</p>
  </body>
</html>

谁能告诉我为什么前者的代码不起作用而后者的代码起作用? 同样,两者都可以在 Chrome 中使用,但第一个在 Mozilla Firefox (32.0) 中存在问题。 提前谢谢你。

注意:不要告诉我更新浏览器(我必须使用它)也不要使用 jquery 或类似的。

【问题讨论】:

标签: javascript html firefox mouseevent


【解决方案1】:

不确定它是否适用于 Firefox,因为我不想使用 Firefox。

<!DOCTYPE html> 
<html>
  <head>
    <title>Test A</title>
    <script>
      function showCoords(evt){
        alert(
          "clientX value: " + evt.clientX + "\n" +
          "clientY value: " + evt.clientY// + "\n"
        );
    	}
      function begin(){
        parag = document.getElementById("parag");
        parag.addEventListener("click", function(e) {showCoords(e);}, false);
      }
    </script>
  </head>
  <body onload="begin()">
    <p id="parag">To display the mouse coordinates click in this paragraph.</p>
  </body>
</html>

【讨论】:

  • 成功了!非常感谢!还要感谢@gurvinder372,他对我的问题发表了评论。
【解决方案2】:

Firefox 没有可用的全局 window.event,即使是最新版本 (53.0),但 Chrome 有。

【讨论】:

    【解决方案3】:

    尝试像这样 begin(event) 将事件发送到 begin 函数,然后将其发送到 js 端的 showCoords 函数

    同样在js中接受事件的时候,你可以试试这个, 事件 = e || windows.event 所以你可以确保所有浏览器都被覆盖

    【讨论】:

    • 在 begin() 中传递事件并不是我真正想要的,因为 begin() 应该仅用于将事件侦听器添加到段落中。无论如何,我仍然尝试了您的两种解决方案,但没有奏效。无论如何谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2019-04-26
    • 2019-02-26
    • 2014-11-19
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多