假设我们有以下输入:
<input id="myInput" type='text' onkeyup="validate(this.value)" />
function validate(character) {
console.log(character)
}
问题是我只能得到输入的总体值。例如,如果我写 2,它会返回 2,但如果我写 7,它会返回 27,而它应该只返回 7。
最佳答案
只需检索 KeyboardEvent
属性 key来自这样的“keyup”事件:
//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'/>
关于javascript - 如何知道输入中输入的最后一个字符 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593603/