简体   繁体   English

Javascript:keydown 事件未触发

[英]Javascript: keydown event not firing

I am writing a userscript with the following code:我正在使用以下代码编写用户脚本:

(function() {
    'use strict';
    window.addEventListener("keydown", arrows, false);
    function arrows(e) {
        debugger;
        switch(e.keycode) {
             case 37: alert("Left"); break;
             case 39: alert("Right"); break;
        }
    }
})();

Eventually the left and right cases will navigate to the previous and next articles in a series, respectively, with something like:最终,左侧和右侧案例将分别导航到系列中的上一篇和下一篇文章,例如:

window.location = String(parseInt(window.location.href.match(/\d+$/))-1);

However, pressing the arrow keys does not cause an alert.但是,按箭头键不会引起警报。 The script is clearly loaded, the Chrome developer menu shows the arrows() function is registered as an event listener for window.keydown , and yet the function never fires.脚本已明确加载,Chrome 开发人员菜单显示arrows()函数已注册为window.keydown的事件侦听window.keydown ,但该函数从未触发。 I added debugger;我添加了debugger; to the arrows() function, but the debugger does not show when I press the arrow keys.arrows()函数,但当我按下箭头键时调试器不显示。

The event propagation is probably getting stopped at some point on the handler for an element, before it bubbles up to window (probably due to a poorly-written onkeydown returning false to prevent the default action, not caring that this also stops propagation). 事件传播可能在元素的处理程序上的某个点停止,然后它冒泡到window (可能是由于写得不好的onkeydown返回false以防止默认操作,而不关心这也会停止传播)。

You should attach your listener with capturing , so that it will capture the event at window , before it bubbles:您应该拍摄附上您的监听器,这样它会在捕获事件window ,它泡

// note the third parameter
window.addEventListener("keydown", arrows, true);

You have mispelled the keyCode:您拼错了 keyCode:

switch(e.keyCode) { // Code is uppercase
    case 37: alert("Left"); break;
    case 39: alert("Right"); break;
}

Your events might be being caught as expected.您的事件可能会按预期被捕获。 Use console.log instead of alert to validate that event got caught.使用console.log而不是alert来验证事件是否被捕获。 Reasons why it does not work with alert are unknown for me: I suspect it has something to do with event fire timing and alert dialogs stopping normal workflow我不知道它不能与alert一起使用的原因:我怀疑它与事件触发时间和警报对话框停止正常工作流程有关

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

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