javascript 将文本框绑定到“输入”键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5943954/
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 textbox to 'enter' key
提问by slandau
I need to bind the 'enter' key on the keyboard to a specific javascript method, but ONLY when a certain text field is in focus.
我需要将键盘上的“回车”键绑定到特定的 javascript 方法,但仅当某个文本字段处于焦点时。
<input id="post" type="text" style="width:400px;"/>
How would I do this?
我该怎么做?
I know you can do it with forms and stuff that have a submit action, but can I just bind the 'enter' key to a specific function when this above input
field is in focus?
我知道您可以使用具有提交操作的表单和内容来执行此操作,但是当上述input
字段处于焦点时,我可以将“输入”键绑定到特定功能吗?
回答by Raynos
$("#post").focus(function() {
$(this).data("hasfocus", true);
});
$("#post").blur(function() {
$(this).data("hasfocus", false);
});
$(document.body).keyup(function(ev) {
// 13 is ENTER
if (ev.which === 13 && $("#post").data("hasfocus")) {
...
}
});
I recommend you instead bind the the ENTER keyup event on your $("#post")
input directly rather then listening for the event on the entire page.
我建议你$("#post")
直接在你的输入上绑定 ENTER keyup 事件,而不是在整个页面上监听事件。
回答by nnnnnn
Just bind the onkeyup event to the input in question. You don't need to worry about checking focus at all, because by definition that input will only receive keyup events when it has focus.
只需将 onkeyup 事件绑定到有问题的输入。您根本不需要担心检查焦点,因为根据定义,输入只会在获得焦点时接收 keyup 事件。
I assume JQuery is OK since you included the tag in your question, so within your document ready handler do something like this:
我认为 JQuery 没问题,因为你在你的问题中包含了标签,所以在你的文档就绪处理程序中做这样的事情:
$("#IDforyourcontrol").keyup(function(ev) {
// 13 is ENTER
if (ev.which === 13 && /*whatever other conditions you care about*/) {
// do something
}
});