jQuery – keydown()在div不工作在Firefox

我有以下示例代码,当div处于焦点并按下某个键时,应该popup警告。 这是我所期望的IE 7,但不是在Firefox 3.5.5。 我究竟做错了什么?

<html> <head> <title>JS test</title> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#testdiv").keydown(function(event) { alert("Pressed " + event.keyCode); }); }); </script> <style type="text/css"> #testdiv { width: 50; height: 50; background-color: red; } </style> </head> <body> <div id="testdiv"></div> </body> </html> 

编辑 :我只是试图用keydownkeyupreplacekeydown ,那些也不工作。 顺便说一句,我也确保我的“Find as you type”设置被closures,以防万一。

你需要给这个div一个tabindex,这样它才能获得焦点。

 <div id="testdiv" tabindex="0"></div> 

我不希望这会起作用,因为div不是应该接收这样的关键事件的东西。 如果您在该div内放置了<input>,并且用户在input本身中按下了一个键,则该事件将冒泡到div并运行您的函数。 我不是100%确定你的项目正在做什么,所以我不知道如何给你更多的build议,但即使我不应该,我有点惊讶IE浏览器正在发射一个关键事件一个div

我得到了上面的工作在Firefox,像这样:

 $('#domainTableDiv').keydown(function(e) { alert(e.type + " button(" + e.which + ") ctrl(" + e.metaKey + ") alt(" + e.altKey + ") shift(" + e.shiftKey + ")" ); }); $('#domainTableDiv').focus(); 

一旦DIV明确地设置了焦点,关键事件在Firefox 4.0.1中就可以正常工作了

我们也可以使用这样的东西:

 $('#tbl tbody').attr("tabindex", 1).focus(); $('#tbl tbody').keydown(function (event) { ... }); 

你可以从这里在线查询

源代码

 <html> <head> <title>JS test</title> <script type="text/javascript"> $(document).ready(function() { $("#testdiv").keydown(function(event) { alert("Pressed " + event.keyCode); }); }); </script> <style type="text/css"> #testdiv { width: 50px; height: 50px; background-color: red; } </style> </head> <body> <div id="testdiv" tabindex="0"></div> </body> </html> 

我无法得到任何这些答案在Firefox 5中使用jQuery的最新CDN。 我需要知道是否有一个关键事件的孩子,所以我诉诸于此:

 $(document).keypress(function(e){ if(!$(e.target).parents().is("#testdiv")) return; /* do child-of-div specific code here */ } 

如果目标是当前的分区(它有焦点),我想你可以做这样的事情:

 $(document).keypress(function(e){ if(!$(e.target).is("#testdiv")) return; /* do div specific code here */ } 

这是因为jQuery版本。 尝试http://code.jquery.com/jquery-latest.js作为源代码;