使用 jQuery 捕获“删除”按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1116244/
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-08-26 10:42:24  来源:igfitidea点击:

Capturing "Delete" Keypress with jQuery

jquerykeypress

提问by Shane H

When using the example code from the jQuery documentation for the keypress event handler, I'm unable to capture the Deletekey. The snippet below is going to log 0when the Deletekey is pressed in FireFox:

将 jQuery 文档中的示例代码用于 keypress 事件处理程序时,我无法捕获Delete密钥。下面的代码片段将在 FireFox 中按下0Delete键时记录:

$(document).keypress(function(e) {
    console.log(e.which);       
});

Seems there's gotta be a way to capture the Deletekey, but it's an ambiguous term so Google isn't proving to be much help with it.

似乎必须有一种方法来捕获Delete密钥,但这是一个模棱两可的术语,因此 Google 并没有证明对此有多大帮助。

回答by Philippe Leybaert

You shouldn't use the keypressevent, but the keyupor keydownevent because the keypressevent is intended for real (printable) characters. keydownis handled at a lower level so it will capture all nonprinting keys like deleteand enter.

您不应使用keypress事件,而应使用keyuporkeydown事件,因为该keypress事件适用于真实(可打印)字符。keydown在较低级别处理,因此它将捕获所有非打印键,如deleteenter

回答by Tod Palin

$('html').keyup(function(e){
    if(e.keyCode == 46) {
        alert('Delete key released');
    }
});

Source: javascript char codes key codesfrom www.cambiaresearch.com

来源:来自 www.cambiaresearch.com 的javascript 字符代码关键代码

回答by csonuryilmaz

Javascript Keycodes

Javascript 键码

  • e.keyCode== 8 for backspace
  • e.keyCode== 46 for forward backspaceor deletebutton in PC's
  • e.keyCode== 8 为backspace
  • e.keyCode== 46 forforward backspacedeletePC 中的按钮

Except this detail Colin & Tod's answer is working.

除了这个细节,科林和托德的回答是有效的。

回答by Gibolt

event.key === "Delete"

event.key === "删除"

More recent and much cleaner: use event.key. No more arbitrary number codes!

更新更干净:使用event.key. 没有更多的任意数字代码!

document.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Delete") {
        // Do things
    }
});

Mozilla Docs

Mozilla 文档

Supported Browsers

支持的浏览器