我有以下输入:
<input id="myInput" type='text' onkeyup="validate(this)" />
在我的 .js 文件中,我有:
var input = document.getElementById("myInput");
input.addEventListener("keyup", function (e) {
console.log(e.key);
});
function validate(characters) {
console.log(characters.value);
}
我的问题是:我可以删除最后输入的字符对应的e.key
吗?
Note:
Deleting the last character of characters is not a solution, since the character can be placed in any position.
最佳答案
您可以根据插入符的位置来做到这一点
const input = document.querySelector('input')
input.addEventListener("keyup", e => {
const position = e.target.selectionStart
input.value = input.value.substring(0, position-1) + input.value.substring(position+1)
})
<input type="text"/>
或者您可以跟踪更改
const input = document.querySelector('input')
let previousValue = input.value
input.addEventListener("keyup", e => {
// if it matches your condition
input.value = previousValue
// reassign so that it works again next time
previousValue = input.value
})
<input type="text"/>
当然,您需要向其中添加条件,否则您根本无法输入内容。并检查按下了哪些键,因为有些键不会添加字符(甚至删除一些字符)。您可能想查看“change”
事件而不是“keyup”
。
关于javascript - 删除输入中输入的最后一个字符 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59595038/