Javascript 将回车键绑定到页面上的特定按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6542413/
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
Bind enter key to specific button on page
提问by slandau
<input type="button" id="save_post" class="button" value="Post" style="cursor:pointer;"/>
How can I bind the enter key on the persons keyboard to this specific button on the page? It's not in a form, and nor do I want it to be.
如何将人员键盘上的回车键绑定到页面上的这个特定按钮?它不是一种形式,我也不希望它是。
Thanks!
谢谢!
回答by Chris Laplante
This will click the button regardless of where the "Enter" happens on the page:
无论“Enter”发生在页面上的何处,这都会单击该按钮:
$(document).keypress(function(e){
if (e.which == 13){
$("#save_post").click();
}
});
回答by Abhishek Hingorani
If you want to use pure javascript :
如果你想使用纯 javascript:
document.onkeydown = function (e) {
e = e || window.event;
switch (e.which || e.keyCode) {
case 13 : //Your Code Here (13 is ascii code for 'ENTER')
break;
}
}
回答by Parham
using jQuery :
使用 jQuery :
$('body').on('keypress', 'input', function(args) {
if (args.keyCode == 13) {
$("#save_post").click();
return false;
}
});
Or to bind specific inputs to different buttons you can use selectors
或者将特定输入绑定到不同的按钮,您可以使用选择器
$('body').on('keypress', '#MyInputId', function(args) {
if (args.keyCode == 13) {
$('#MyButtonId').click();
return false;
}
});
回答by Alexander Kim
回答by Josh Brunton
Maybe not quite what you're looking for but there is a HTML property that lets you assign a specific button called an access key to focus or trigger an element. It's like this:
可能不是您想要的,但是有一个 HTML 属性可以让您分配一个称为访问键的特定按钮来聚焦或触发一个元素。就像这样:
<a href='https://www.google.com' accesskey='h'>
This can be done with most elements.
大多数元素都可以做到这一点。
Here's the catch: it doesn't always work. for IE and chrome, you need to be holding alt as well. On firefox, you need to be holding alt and shift (and control if on mac). For safari, you need to be holding control and alt. On opera 15+ you need alt, before 12.1 you need shift and esc.
这里有一个问题:它并不总是有效。对于 IE 和 chrome,您还需要按住 alt。在 Firefox 上,您需要按住 alt 和 shift(如果在 mac 上,则需要控制)。对于 safari,您需要保持控制和 alt。在 Opera 15+ 上你需要 alt,在 12.1 之前你需要 shift 和 esc。
Source: W3Schools
资料来源:W3Schools