开发者

keydown on body?

开发者 https://www.devze.com 2022-12-20 01:42 出处:网络
I want to get alerted whenever I press a key. I\'ve tried: $(\'body\').live(\'keyup\', function() { alert(\'testing\');

I want to get alerted whenever I press a key.

I've tried:

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

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

UPDATE:

Here is my code:

<!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(fu开发者_StackOverflow中文版nction() {
                $('body').live('keyup', function() {
                    alert('testing');
                });   
            });   
        </script>
    </head>
    <body>
        <p>
            TODO write content
        </p>
    </body>
</html>

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

Why doesn't it work?


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(...);


Just listen to the window!

$(window).keydown(function(event){
    alert(event.keyCode);
});


I tried this code. This is working fine.

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


It does not work because your page does not have focus.. you need to click on the page first and it will work..

alternatively you could forcibly set the focus to an input element and thus bring focus to the page..

$(function(){ $('input_selector_here').focus(); });


Hope this will help.

$(document.body).on('keyup', function (e) {
    alert('In');
}):
0

精彩评论

暂无评论...
验证码 换一张
取 消