首页 > 解决方案 > 添加正则表达式后无法从输入中删除文本

问题描述

我有这个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;
    })

我遇到的问题是当输入的值达到最大长度(我在代码中规定)时,我无法删除文本。

我不知道是什么导致了这个问题。

标签: javascript

解决方案


当您达到最大长度时,您将阻止此行中的默认输入行为。删除它并在 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 文档。


推荐阅读