无法删除动态添加的冒号 [英] Can't delete dynamically added colon
问题描述
我需要一个在输入中输入两个数字后添加冒号(:)的函数,我发现此解决方案这里也是StackOverflow,这就是我需要的。它在输入第二个数字后添加冒号,不会让你添加超过4个数字。
I need a function that will add the colon (:) after you type two numbers in input and I found this solution here on StackOverflow as well which is what I need. It add colon after typed second number and won't let u add more than 4 numbers.
然而,有一个我无法理解和解决的问题。我需要删除所有数字,但它不会让我。我只能删除最后两个,你不能删除冒号。
However, there is an issue that I can't understand and solve. I need to be able to delete all numbers, but it won't let me. I can delete only last two, and you can't delete colon.
这是当前代码:
var time = document.getElementsByClassName('time');
for (var i = 0; i < time.length; i++) {
time[i].addEventListener('keyup', function (e) {
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
});
};
https://jsfiddle.net/bubxm7pe/
推荐答案
您可以使用<$添加退格条件c $ c> e.keyCode
它有效这里
if (e.keyCode != 8)
{
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
}
更新:您还可以使用以下数字来限制用户。它也适用于此处
Update: You can also restrict user with digits like following. It also works here
//called when key is pressed in textbox
$(".time").keypress(function (e) {
//if the letter is not digit then don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
else
{
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 4) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
}
});
这篇关于无法删除动态添加的冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!