jQuery:按J并让它做某事,按H并让它做其他事情

时间:2010-09-23 08:09:17

标签: javascript jquery keypress

我无法得到一个简单的答案:当我按下字母J时,我希望它隐藏$('.something'),当我按下字母H时,我希望它显示$('.something') < / p>

press the letter J
$('.something').hide()

press the letter H
$('.something').show()

3 个答案:

答案 0 :(得分:5)

$(document).bind('keydown', function(e) {
    if (e.keyCode == 72) {
        // press the letter H
        $('.something').show()
    } else if (e.keyCode == 74) {
        //press the letter J
        $('.something').hide()
    }
    return false;
});​

crazy demo

答案 1 :(得分:0)

document.addEventListener('keypress', function(e) {
    if (String.fromCharChode(e.charCode) == 'j') $('.something').hide();
    if (String.fromCharChode(e.charCode) == 'h') $('.something').show();
}, false);

答案 2 :(得分:0)

基于字符的密钥检测只能通过keypress事件完成:

$(document).keypress(function(e) {
    var charCode = e.which;
    if (charCode) {
        var lowerCharStr = String.fromCharCode(charCode).toLowerCase();
        if (lowerCharStr == "h") {
            $('.something').show();
        } else if (lowerCharStr == "j") {
            $('.something').hide();
        }
    }
});