javascript ReferenceError: 事件未在 mozila firefox 中定义

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

ReferenceError: event is not defined in mozila firefox

javascriptfirefoxjavascript-events

提问by Arun Chandran C

This code is not working for me in firefox(V21.0) but works in IE(V9,V10) and Chrome (V 27.0.1453.110 m)

此代码在 firefox(V21.0) 中不适用于我,但适用于 IE(V9,V10) 和 Chrome (V 27.0.1453.110 m)

method cal:

方法校准:

<input type="text" id="txt1" class="search-bar-input"
                         onkeyup="handleKeyPress('btn1');">

method defenition:

方法定义:

function handleKeyPress(searchButtonId) {
   if (event.keyCode === 13) {
    alert(event.KeyCode);
    }
}

Error Message:

错误信息:

ReferenceError: event is not defined
if (event.keyCode === 13) {

any one have any idea to solve the issue?

任何人有任何想法来解决这个问题?

回答by Arun P Johny

Use

利用

<input type="text" id="txt1" class="search-bar-input" onkeyup="handleKeyPress(event, 'btn1');">

Then

然后

function handleKeyPress(event) {
    event = event || window.event //For IE
    if (event.keyCode === 13) {
        alert(event.keyCode);
    }
}

Demo: Fiddle

演示:小提琴

回答by MrCode

You could store the btn1parameter as a data-*attribute and use unobtrusive Javascript to assign the event handler (instead of inline).

您可以将btn1参数存储为data-*属性并使用不显眼的 Javascript 来分配事件处理程序(而不是内联)。

Also your line alert(event.KeyCode);is wrong, the Kin KeyPressshould be lowercase k.

你的行alert(event.KeyCode);也是错误的,KinKeyPress应该是小写的k

Fiddle

小提琴

HTML

HTML

<input type="text" id="txt1" class="search-bar-input" data-searchButtonId="btn1" />

Javascript:

Javascript:

function handleKeyPress(event) {
   if (event.keyCode === 13) {
        console.log(event.keyCode + this.getAttribute("data-searchButtonId"));
   }
}

window.onload = function(){
   document.getElementById("txt1").onkeyup = handleKeyPress;   
}