gpt4 book ai didi

javascript - 长度 - 1 比 JS 中应有的长度要长

转载 作者:行者123 更新时间:2023-12-01 01:16:03 25 4
gpt4 key购买 nike

我的代码遇到了一个奇怪的问题。每次用户按下退格键时,都会从末尾删除三个数字。我目前正在使用 $(this).val($(this).val().substring(0, $(this).val().length - 1));从末尾去掉一个数字,但删除的数字超出了应有的数字。我做错什么了吗?

on('keydown keyup', '.type-date', function(e) {
$(this).attr('maxlength', '10');
var value = $(this).val();
var key = String.fromCharCode(e.keyCode);
if (!(key >= 0 && key <= 9))
$(this).val($(this).val().substring(0, $(this).val().length - 1));
if (value.length == 2 || value.length == 5)
$(this).val($(this).val() + '/');
$('.type-date').attr('value', value);
});

最佳答案

该函数在 keydown 上执行两次,然后在 keyup 上执行。只需在 keyup

上触发函数

$('.type-date').on('keyup', function(e) {
$(this).attr('maxlength', '10');
var value = $(this).val();
var key = String.fromCharCode(e.keyCode);
if (!(key >= 0 && key <= 9))
$(this).val($(this).val().substring(0, $(this).val().length));
if (value.length == 2 || value.length == 5)
$(this).val($(this).val() + '/');
$('.type-date').attr('value', value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="type-date" />

关于javascript - 长度 - 1 比 JS 中应有的长度要长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54754039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com