javascript 如何将键盘事件绑定到 div 元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10722589/
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
How to bind keyboard events to div elements?
提问by ilyes kooli
Is there a way to listen to keyboard events on a DIV element?
有没有办法在 DIV 元素上监听键盘事件?
My code:
我的代码:
?<div id="div" style="height:50px" class="ui-widget-content"></div>
<input id="input">??????????????
?$('#div,#input').keyup(function(event){
console.log(event.keyCode);
});??????
Actually, the code triggers only for the input, can I handle it for the div?
其实代码只对输入触发,我可以为div处理吗?
回答by Prasenjit Kumar Nag
回答by Selvakumar Arumugam
回答by mkoryak
you need to add a tabindex to the div.
您需要向 div 添加一个 tabindex。
see this fiddle:
看到这个小提琴:
回答by Brian Scott
Why not place the input inside the div and then simply find $('#input').closest('div') ?
为什么不将输入放在 div 内,然后简单地找到 $('#input').closest('div') ?
Otherwise, if your example is a pattern of how your inputs relate to your divs then simply $('#input').prev() ?
否则,如果您的示例是您的输入如何与您的 div 相关的模式,那么只需 $('#input').prev() ?