使用 jQuery on 函数绑定到 keydown 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18370856/
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
Binding to the keydown event with jQuery on function
提问by Eae
sqHTML = "<div id=\""+sqStringTemp+"\" class=\"puzzlesquare\"><input type=\"text\" class=\"puzzlesquareinput\" maxlength=\"1\" style=\"text-transform: uppercase\"/></div>";
jQuery("#gridpuzzleouter").append(sqHTML);
jQuery(".puzzlesquareinput").on('keydown', '', function() {
alert("keydown...");
});
I am not yet getting any alert out of .puzzlesquareinput
. I am wondering how to bind to the keydown event of each .puzzlesquareinput
.
我还没有收到任何警报.puzzlesquareinput
。我想知道如何绑定到每个 .keydown 事件.puzzlesquareinput
。
回答by Reigel
jQuery(".puzzlesquareinput").on('keydown', function() {
alert("keydown...");
});
your current code is working... make sure there are no javascript error... and/or wrap your code on $(document).ready
... try checking the console...
您当前的代码正在运行...确保没有 javascript 错误...和/或包装您的代码$(document).ready
...尝试检查控制台...
here's a fiddle of your current code which is working http://jsfiddle.net/reigel/fcTqP/
这是您当前正在运行的代码的小提琴http://jsfiddle.net/reigel/fcTqP/
回答by Adil
You need to delegate event to parent of .puzzlesquareinput
that is #gridpuzzleouter
in your case. Ensure you included jquery successffullyand bind event in document.ready.
在您的情况下.puzzlesquareinput
,您需要将事件委托给父级#gridpuzzleouter
。确保您成功包含 jquery并在document.ready 中绑定事件。
Change to
改成
jQuery("#gridpuzzleouter").on('keydown', '.puzzlesquareinput', function() {
alert("keydown...");
});
回答by u283863
jQuery(".puzzlesquareinput").on('keydown', '', function() {
^this is the selector, and you are
selecting nothing
There is no point doing that unless you want it to apply to all .pzzlesquareinput
you later created. Try this instead:
除非您希望它应用于.pzzlesquareinput
您以后创建的所有内容,否则这样做毫无意义。试试这个:
$(".puzzlesquareinput").keydown(function(){
//...
});
<input class="puzzlesquareinput">