sla*_*dau 10 html javascript jquery
我需要将键盘上的"enter"键绑定到特定的javascript方法,但仅限于某个文本字段处于焦点时.
<input id="post" type="text" style="width:400px;"/>
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
我知道你可以用表单和具有提交动作的东西来做,但是当上面的input
字段是焦点时,我可以将'enter'键绑定到特定的函数吗?
Ray*_*nos 18
$("#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")) {
...
}
});
Run Code Online (Sandbox Code Playgroud)
我建议您$("#post")
直接在输入上绑定ENTER keyup事件,而不是在整个页面上侦听事件.
nnn*_*nnn 13
只需将onkeyup事件绑定到相关输入即可.您根本不需要担心检查焦点,因为根据定义,输入只有在具有焦点时才会收到键盘事件.
我假设JQuery没问题,因为你在你的问题中包含了标记,所以在你的文档就绪处理程序中做了类似这样的事情:
$("#IDforyourcontrol").keyup(function(ev) {
// 13 is ENTER
if (ev.which === 13 && /*whatever other conditions you care about*/) {
// do something
}
});
Run Code Online (Sandbox Code Playgroud)