javascript 按回车键执行功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16011312/
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
execute function on enter key
提问by frrlod
I have an input and I'd simply like to add an event listener for it to activate a function when I press enter, when the input is focused. How do I do this with pure JS?
我有一个输入,我只想为它添加一个事件侦听器,以便在输入聚焦时按 Enter 激活一个功能。我如何用纯 JS 做到这一点?
Right now I have:
现在我有:
HTML:
HTML:
Enter your wage:<input type="text" id="wage" value ="" size=20>
<button id="sub">Submit</button>
Javascript:
Javascript:
var wage = document.getElementById("wage");
wage.addEventListener("change", validate);
var btn = document.getElementById("sub");
btn.addEventListener("click", validate);
So basically the function validate() activates when I click OR change the text, but I want to call it by pressing enter.
所以基本上,当我单击或更改文本时,validate() 函数会激活,但我想通过按 Enter 键来调用它。
回答by Minko Gechev
You can use this:
你可以使用这个:
var wage = document.getElementById("wage");
wage.addEventListener("keydown", function (e) {
if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
validate(e);
}
});
function validate(e) {
var text = e.target.value;
//validation of the input...
}
回答by Kevin Bowersox
var elem = document.getElementById("wage");
elem.onkeyup = function(e){
if(e.keyCode == 13){
validate();
}
}
Working Examplehttp://jsfiddle.net/aMgLK/
回答by Marcus
Here is a version of the currently accepted answer (from @MinkoGechev) with keyinstead of keyCode:
这是当前接受的答案(来自@MinkoGechev)的一个版本,其中包含key而不是 keyCode:
const wage = document.getElementById('wage');
wage.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
validate(e);
}
});
function validate(e) {
const text = e.target.value;
//validation of the input...
}
回答by gvhuyssteen
If you change your button element to a
如果您将按钮元素更改为
<input type="submit" value="Submit">
it will work with the enter button on your keyboard.
它将与键盘上的输入按钮一起使用。
回答by scoota269
You would need something like
wage.addEventListener('keydown', validate);
你需要类似的东西
wage.addEventListener('keydown', validate);
Your validate function would then need to check event.keyCode == 13
to determine 'enter' keypress.
然后您的验证功能需要检查event.keyCode == 13
以确定“输入”按键。
回答by klaasjan69
Or with jQuery
或者使用 jQuery
$("#wage").on("keydown", function (e) {
if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
validate(e);
}
});
回答by manoj yadav
$(document).on("keyup", function(e) {
var key = e.which;
if (key == 13) // the enter key ascii code
{
login();
}
});