首页 > 解决方案 > 如何知道输入中的最后一个字符 - Javascript

问题描述

假设我们有以下输入:

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

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

问题是我只得到输入的整体价值。例如,如果我写 2,它会返回 2,但如果我写 7,它会返回 27,而它应该只返回 7。

标签: javascriptinputkeyboard-eventsonkeyup

解决方案


只需 从“keyup”事件中检索KeyboardEvent属性键,如下所示:

//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'/>


推荐阅读