身上的keydown? [英] keydown on body?

查看:60
本文介绍了身上的keydown?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我按一个键时,我都会收到提醒。

I want to get alerted whenever I press a key.

我试过:

$('body').live('keyup', function() {
     alert('testing');
});

但它不起作用,是不是因为选择器?

But it doesn't work, could it be because of the selector?

更新:

这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>TODO supply a title</title>
        <script type="text/javascript" src="../system/media/js/jquery/jquery.js"></script>
        <script type="text/javascript">  
            $(document).ready(function() {
                $('body').live('keyup', function() {
                    alert('testing');
                });   
            });   
        </script>
    </head>
    <body>
        <p>
            TODO write content
        </p>
    </body>
</html>

当我按下某些内容时它不会提示我,但是当我更换 keyup ,鼠标悬停并将鼠标悬停在 TODO写内容

It doesn't alert me when I press something although it works when I replace keyup with mouseover and mouse over TODO write content

为什么不起作用?

推荐答案

尝试使用 $( html) $(*)而不是 $(body)。为了触发正文上的 keyUp 事件,必须关注正文节点或其中一个子节点。您可以在示例中通过添加文本输入并将鼠标聚焦到该输入来完成此操作。你真正想要的是捕获任何按键,所以 $(html)应该有效。

Try using $("html") or $("*") instead of $("body"). In order for the keyUp event on body to fire, the body node or one of its children must be focused. You can accomplish this in your example by adding a text input and focusing the mouse to that input. What you really want is to capture any key press, so $("html") should work.

编辑:我认为您的示例可能有效,但无论如何,要有条件地运行逻辑,您可以尝试这样做:

Edit: I think your example might work, but in any case, to run the logic conditionally you might try this:

if ($(document.body).is(".focusOnKeypress")) {
   $("html").live(...);
}

或者,我认为这也有效:

Or, I think this will also work:

$("body:not(.noFocusOnKeypress)").parent("html").live(...);

这篇关于身上的keydown?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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