Javascript 通过Javascript按下回车按钮时调用函数

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

Call a function when the enter button is pressed via Javascript

javascripthtml

提问by Fred Vicentin

I have a problem, I want to call a function inside a textbox, when I press enter, this is my code

我有一个问题,我想在文本框中调用一个函数,当我按回车键时,这是我的代码

<input  type="text" value="DIGITE O LOCAL" onclick="this.select()" size="20" id="endereco">

I want to put something like onenterpress="doSomething()"

我想放一些东西 onenterpress="doSomething()"

How can I do this ?

我怎样才能做到这一点 ?

回答by Daniel Li

If you want to use obtrusive Javascript:

如果你想使用突兀的 Javascript:

<input type="text" value="DIGITE O LOCAL" onclick="this.select()" 
onKeyDown="if(event.keyCode==13) alert(5);" size="20" id="endereco">

Handling this unobtrusively:

不显眼地处理这个:

document.getElementById('endereco').onkeydown = function(event) {
    if (event.keyCode == 13) {
        alert('5');
    }
}

Your best choice is to use the latter approach. It will aid in maintainability in the long run.

您最好的选择是使用后一种方法。从长远来看,它将有助于可维护性。

Reference: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

参考http: //en.wikipedia.org/wiki/Unobtrusive_JavaScript

回答by 2stripe

Daniel Li's answeris the slickest solution, but you may encounter a problem with IE and event.keyCode returning undefined, as I have in the past. To get around this check for window.event

Daniel Li 的回答是最巧妙的解决方案,但您可能会遇到 IE 和 event.keyCode 返回 undefined 的问题,就像我过去遇到的那样。要绕过此检查 window.event

document.getElementById('endereco').onkeydown = function(event){
    var e = event || window.event;
    if(e.keyCode == 13){
        alert('5');
    }
}?

回答by AlienWebguy

HTML

HTML

<input  type="text" value="DIGITE O LOCAL" onkeypress="doSomething(this, event)" onclick="this.select()" size="20" id="endereco">

JS

JS

function doSomething(element, e) {
    var charCode;

    if(e && e.which){
        charCode = e.which;
    }else if(window.event){
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13) {
        // Do your thing here with element
    }
}