简体   繁体   English

使用javaScript捕获按键事件

[英]capturing on key press event using javaScript

in below example , searchForward gets called when Shift key is pressed 在下面的示例中, 当按Shift键时会调用searchForward
however searchBackward never gets called when Shift + tab key is pressed. 但是, 当按Shift + Tab键时,永远不会调用searchBackward。 Please suggest. 请提出建议。

$(document).ready(function() {

    $('textarea').live('keydown', function(e) {
      // var keyCode = e.keyCode || e.which;
        if (e.which == 9 ) {    
        var currentIndex = getCaret($(e.target).get(0))
        searchForward($(e.target), currentIndex);
        return false
        } 
        if (e.shiftkey) {
         var currentIndex = getCaret($(e.target).get(0))
        searchBackward($(e.target), currentIndex);
        return false 
       }
    });
});

On your second if , you are only checking for the shift key, not for shift and the key pressed. 在第二个if ,您仅检查Shift键,而不检查Shift和按下的键。 You need to put your second if loop inside the first. 您需要将第二个if循环放入第一个。 Also, I beleive you meant shiftKey , not shiftkey . 另外,我相信你的意思是shiftKey ,而不是shiftkey JavaScript is case sensitive. JavaScript区分大小写。 Take a look at the updated snippet (also moved duplicate code outside the if ): JSFiddle 看一下更新的代码段(还将重复代码移到if之外): JSFiddle

$(document).ready(function() {
    $('textarea').live('keydown', function(e) {
        var currentIndex = getCaret($(e.target).get(0))
        if (e.which == 9 ) {
            if (e.shiftKey) {
                searchBackward($(e.target), currentIndex);
            } else {
                searchForward($(e.target), currentIndex);
            }
            return false
        }
    });
});

Also see JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink? 另请参见JQuery或JavaScript:如何确定在单击锚标记超链接时是否按下了Shift键?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM