在用户首先单击页面之前,jquery keyup不会被触发
我正在尝试使用jQuery中的keyup设置一些简单的页面导航。 例如,如果用户按下左箭头键,我希望页面加载一些东西。
一切正常,但用户必须先点击浏览器窗口才能注册关键事件。
这是我正在使用的代码:
$(document).ready(function() { $(document.documentElement).live("keyup", function(event) { if (event.keyCode == 37) {//left arrow //do something here } }); });
这似乎是一个焦点问题,但我已经读过使用document.documentElement
意味着我不必专注于任何特定的事情。
如果用户在页面上单击一次然后点击其左箭头,则它可以工作。 但如果他们加载页面并点击左箭头而不点击它就不会开火。
有任何解决这个问题的方法吗?
您的页面没有focus
它,这就是您need to click
页面的原因。 将注意力集中在一些控制上然后它将起作用。 live在这种情况下不会造成任何麻烦但是开始使用而不是生活是贬低的。
我通过状态$('#txt1').focus();
设置焦点$('#txt1').focus();
评论此声明,您将注意到您必须单击该页面才能获得keyup事件。
现场演示
$(document).ready(function() { $('#txt1').focus(); //This is the statement that puts focus on page $(document.documentElement).live("keyup", function(event) { if (event.keyCode == 37) {//left arrow //do something here alert(""); } }); });
尝试使用.on()
并且不使用委托事件处理。
$(document).ready(function() { $(document).on("keyup", function(event) { if (event.which == 37) {//left arrow //do something here } }); });
或者使用.keyup()
方法:
$(document).ready(function() { $(document).keyup(function(event) { if (event.which == 37) {//left arrow //do something here } }); });
在这里,您不需要live
(不建议使用)和document.documentElement
。
不推荐使用.live()
函数。 试试这个:
$(document).ready(function() { $('body').on("keyup", function(event) { if (event.keyCode == 37) {//left arrow //do something here } }); });
不需要使用已弃用的live
或on
,因为您还有文档。
此外,无需使用document.documentElement
。
简单地做
$(document).keydown(function(){ });
这很好用,不需要点击。