javascript 执行 ESC 键的点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6415299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:35:15  来源:igfitidea点击:

Execute onclick of ESC Key

javascriptjqueryjavascript-eventsesc-key

提问by Hamza

Briefly, my problem is that I would like to execute the effect of Escbutton by a line of javascript, for example execute an effect onclick of the Escbutton. How can I do It ?

简而言之,我的问题是我想Esc通过一行 javascript来执行按钮的效果,例如在Esc单击按钮时执行效果。我该怎么做 ?

[ What I have is an upload in a jQuery box, so I would like that when the upload will finish, the escape function will be executed automatically to close the box]

[我有一个jQuery框的上传,所以我希望当上传完成时,会自动执行转义功能以关闭框]

回答by pMan

I know it's an old question. However if somebody lands in here on search, it may help:

我知道这是一个老问题。但是,如果有人在这里进行搜索,它可能会有所帮助:

First, trigger the event on desired element (or document),

首先,在所需元素(或文档)上触发事件,

$('a[name=close]').click(function(){
    var e = jQuery.Event("keyup"); // or keypress/keydown
    e.keyCode = 27; // for Esc
    $(document).trigger(e); // trigger it on document
});

And then, have a keyup listener on document:

然后,在文档上有一个 keyup 侦听器:

// Esc key action
$(document).keyup(function(e) {
    if (e.keyCode == 27) { // Esc
        window.close(); // or whatever you want
    }
});

回答by manish

This code works for me

这段代码对我有用

$(document).keyup(function(e) {     
    if(e.keyCode== 27) {
        alert('Esc key is press');  
    } 
});