简体   繁体   English

跟踪在输入字段中是否按了退格键或Delete键

[英]Tracking if backspace or delete key is pressed in an input field

I was wondering how i can track if users hit the backspace or delete key in a input field. 我想知道如何跟踪用户是否在输入字段中按了退格键或删除键。 Afterwhich i would add to a variable called count each time those buttons are pressed. 之后,每次按下这些按钮时,我都会添加一个名为count的变量。 I currently have this code but it does not seem to work; 我目前有此代码,但它似乎无法正常工作。 any help is great appreciated, thank you. 任何帮助都非常感谢,谢谢。

var Count = 0;

var input = document.getElementById('display');

input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        Count++;
        return false;
};

multiple lines inside a conditional or loop, etc. need to be wrapped in braces: 条件或循环等中的多行需要用大括号括起来:

if( key == 8 || key == 46 )
{
    Count++;
    return false;
}

You will also want to add a default return true as the last line to differentiate whether you entered the if or not as well. 您还需要添加默认的return true作为最后一行,以区分是否也输入了if。

Try this approach: 试试这种方法:

var count = 0;

var input = document.getElementById('display');

input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    if( key !== 8 && key !== 46 )
        return true;

    count++;
};
  1. Don't start your variable names with a capital letters unless they are object prototypes you're going to instantiate, ie. 除非变量名是要实例化的对象原型,否则不要以大写字母开头。 var count = new Count( ) , where you previously defined the Count object prototype var count = new Count( ) ,您之前在其中定义了Count对象原型

  2. Always use a strict comparator, like === and !== , don't just use == and != 始终使用严格的比较器,例如===!== ,而不仅仅是使用==!=

  3. Check for negative first, and return true if your condition doesn't match. 首先检查是否为负,如果条件不匹配,则返回true。 Then execute your code, in your case count++ 然后执行您的代码,具体情况count++

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

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