javascript - 如何知道输入中的最后一个字符 - Javascript
问题描述
假设我们有以下输入:
<input id="myInput" type='text' onkeyup="validate(this.value)" />
function validate(character) {
console.log(character)
}
问题是我只得到输入的整体价值。例如,如果我写 2,它会返回 2,但如果我写 7,它会返回 27,而它应该只返回 7。
解决方案
只需 从“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'/>
推荐阅读
- html - jquery不会从另一个图像设置图像src
- r - 数据点未显示在 R Shiny 散点图中
- javascript - p5 绘画应用程序:更精确的铅笔可能吗?最近的 pmouseX/Y?
- python - CS50 credit.py 尝试通过转换为整数来添加字符串的总和
- c++ - C++ MySql 连接器问题
- javascript - 每次单击带有事件侦听器的元素时,都会触发元素 innerHTML +=。但它只触发一次
- python - 在pygame中的边界上反转方向
- c++ - 为什么当我将一个整数变量添加到我的类函数时,它会产生错误?
- php - PHP 警告:使用未定义的常量 purchaser_name 和其他
- php - 获取数组 Laravel ->first(); 错误 json_decode() 需要参数