直到用户首先单击页面,jquery keyup才会触发 [英] jquery keyup not fired until user clicks page first

查看:129
本文介绍了直到用户首先单击页面,jquery keyup才会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery中的快捷键设置一些简单的页面导航.例如,如果用户按下向左箭头键,我希望页面加载某些内容.

I'm trying to setup some simple page navigation with keyups in jQuery. For instance, if the user presses the left arrow key, I want the page to load something.

一切正常,除了用户必须首先单击浏览器窗口以注册键事件.

Everything works except the user must first click the browser window for the key event to register.

这是我正在使用的代码:

Here's the code I'm using:

$(document).ready(function() {
  $(document.documentElement).live("keyup", function(event) {
      if (event.keyCode == 37) {//left arrow
        //do something here
      }
  });
});

这似乎是一个焦点问题,但是我已经读到使用document.documentElement意味着我不必特别关注任何事情.

It seems like a focus issue, but I've read that using document.documentElement means I don't have to focus on anything in particular.

如果用户在页面上单击一次然后单击其左箭头,则该方法有效.但是,如果他们加载该页面并单击左箭头而不单击它,则不会触发.

It works if the user clicks once on the page and then hits their left arrow. But if they load the page and hit the left arrow without clicking it doesn't fire.

有什么办法解决这个问题?

Any way to fix this?

推荐答案

您的页面上没有focus,这就是您在页面上need to click的原因.将焦点放在某个控件上,它将起作用.在这种情况下,live不会造成任何麻烦,而是因为已弃用live而开始使用on.

Your page does not have focus on it that is why you need to click on the page. Set focus on some control then it will work. live is not cause any trouble in this case but start using on instead as live is depreacted.

我按状态设置焦点$('#txt1').focus();对此语句进行注释,您会发现您必须单击页面来获取keyup事件.

I set the focus by state $('#txt1').focus(); Comment this statement and you will notice you will have to click the page to get keyup event.

实时演示

Live Demo

$(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("");
      }
  });
});​

这篇关于直到用户首先单击页面,jquery keyup才会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆