如何知道输入的最后一个字符 - Javascript

How to know the last character entered in input - Javascript

假设我们有以下输入:

<input id="myInput" type='text' onkeyup="validate(this.value)" />

function validate(character) {
    console.log(character)
}

问题是我只得到输入的整体值。例如,如果我写 2,它 returns 2 但如果我写 7,它 returns 27,而它应该 return 只有 7。

我能想到的最简单的解决方案是 console.log(character[character.length-1])

您获得整个文本的原因是您为验证函数提供了整个输入值。要检查最后输入的字符,您可以将文本拆分为最后一个字符并检查它。 如果你想允许输入某些字符,你必须每次检查这个字符。

只需从 "keyup" 事件中检索 KeyboardEvent 属性 key,如下所示:

//assign the input element to a variable
let input = document.querySelector("#myInput"); 

//add a keyup listener to the input that will run the function passing the event to the function as an argument
input.addEventListener("keyup", function(e) {
    console.log(e.key);
});
<input id="myInput" type='text'/>

JSFiddle 上面的代码: https://jsfiddle.net/AndrewL64/n18wqzjm/4/


但是等等,如果我想要某些键 运行 其他东西,比如 运行 一个不同的 console.log 呢?

好吧,您可以添加一个条件语句来检查键 属性 值并将其与单个键进行比较,如下所示:

let input = document.querySelector("#myInput");

input.addEventListener("keyup", function(e) {
 if (e.key === "Delete") {
    //if the DELETE key is pressed, don't run the default console.log but do something else
    console.log("You are trying to add delete key as a character: " + e.key);
  } else if (e.key === "Escape") {
    //if the ESCAPE key is pressed, don't run the default console.log but do something else
   console.log("You are trying to add escape key as a character: " + e.key);
  } else {
    //run the default console.log
   console.log(e.key);
  }
});
<input id="myInput" type='text'/>

var input = "String"; 
var result = input.charAt(input.length-1);

输出:g