javascript - 添加正则表达式后无法从输入中删除文本
问题描述
我有这个javascript代码:
document.querySelector('div[data-field-name="CNPJ"] input').addEventListener('keydown', (inheritance) => {
let value = inheritance.target.value;
console.log(value.length)
if (value.length >= 18) {
inheritance.preventDefault()
inheritance.stopPropagation()
return
}
value = value.replace(/\D/g, "")
value = value.replace(/^(\d{2})(\d)/, "$1.$2")
value = value.replace(/^(\d{2}).(\d{3})(\d)/, "$1.$2.$3")
value = value.replace(/.(\d{3})(\d)/, ".$1/$2")
value = value.replace(/(\d{4})(\d)/, "$1-$2")
inheritance.target.value = value;
})
我遇到的问题是当输入的值达到最大长度(我在代码中规定)时,我无法删除文本。
我不知道是什么导致了这个问题。
解决方案
当您达到最大长度时,您将阻止此行中的默认输入行为。删除它并在 HTML 代码中添加一个 maxlength 检查。
if (value.length >= 18) {
inheritance.preventDefault()
inheritance.stopPropagation()
return
}
我不确定为什么需要这一行,因为您可以在 HTML 中执行类似的操作:
<input maxlength="18"></input>
你能详细说明为什么 maxlength 必须在 JavaScript 中完成吗?
或者,您可以在逻辑中添加 Backspace 或类似的键检查:
if (
value.length >= 18
&& inheritance.key !== "Backspace"
) {
inheritance.preventDefault()
inheritance.stopPropagation()
return
}
我不建议亲自检测特定的键,因为 HTML 考虑的边缘情况比单个键检查要多得多。
查看有关输入模式的 MDN 文档。
推荐阅读
- vba - Countifs 函数抛出对象定义错误
- javascript - JS/HTML,引导弹出窗口和可编辑弹出窗口之间的冲突破坏了可编辑的保存数据
- hyperledger-fabric - Hyperledger Cello Operator Dashboard 不断加载
- r - 在 R 中,使用滞后操作时间序列
- class - 如何使用链式方法访问扩展类中的公共变量?
- sql - SQL查找表中第一次出现的行
- wordpress - Wordpress 管理员只显示文本
- odoo-11 - 标题和副标题需要 Odoo 11 网站博客颜色选择器
- php - 我们如何在 PHP 中的 Fatfree 框架中包含语言区域设置
- javascript - 启用搜索框 - 数据表