JavaScript正则表达式中type=number和type=text有什么区别?

3
脚本需要计算3个字符并过滤掉不是数字的任何内容。在任何3个数字之后,脚本会插入“ - ”。然后防止添加超过9位数字。
当我在输入中使用"type=text"时,所有内容都正常工作。当我使用"type=number"时(这对我的新任务很重要),脚本不起作用,(replace(/(.{3})/g,'$1 - ')将最后3个字符放入输入框中[据我猜测])。
我的问题是:
在正则表达式方面是否存在两种类型的区别?
也许"type=number"解析字符串为int? (但据我所知,纯(没有JS)的"type=number"不会实时过滤任何内容)。
附言。 对于可怕的语言表示抱歉。
现在的代码:

$(document).ready(function() {
  var selection = document.querySelector('.correct_phone input[name=phone]');
  //selection.setAttribute('type','number');
  selection.addEventListener('input', function(e) {
    selection.addEventListener('keydown', function(b) {

      if (b.keyCode != 8 && b.keyCode != 46 && b.keyCode != 37 && b.keyCode != 39 && b.keyCode != 16 && b.keyCode != 17 && b.keyCode != 18) {
        if (e.target.value.length < 14 && e.target.value.length > 0) {
          $(selection).parent('.correct_phone').find('.error_list.not_digit').remove();
          //e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{3})/g, '$1 ').trim(); /^\d+$/
          e.target.value = e.target.value.replace(/[^\d]/g, '').replace(/(.{3})/g, '$1 - ').trim();
        } else if (e.target.value.length > 14) {
          $(selection).parent('.correct_phone').find('.error_list.not_digit').remove();
          e.target.value = e.target.value.substring(0, e.target.value.length - 1);
          $(selection).parent('.correct_phone').css('border-color', 'red').find('label').before("<ul style='margin-bottom:0px;' class='error_list not_digit'><li style=' font-size:1.1em;'>Nuber shuld contains only 9 digits</li></ul>");
          $(selection).parent('.correct_phone').find('ul.error_list.not_digit').animate({
            opacity: 0
          }, 3000, function() {
            $(this).remove();
          });
        }
      } else
        $(selection).parent('.correct_phone').find('.error_list.not_digit').remove();
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fieldset semi correct_phone">
  <label class="input-name">Phone:</label>
  <input type="text" name="phone" value="" />


</div>


“type=number”为什么不会过滤实时数据? - Adam Buchanan Smith
在JS中读取值时,“value”和“type of string”没有区别。 - Teemu
为什么你要嵌套事件附加?在oninput处理程序中有addEventListener('keydown',..)。这肯定会给你带来麻烦。顺便说一下,区别在于,如果数字输入类型包含非数字值,则在oninputonchange等处理程序中读取该值为空字符串。此外,看起来onchange在这种情况下只会触发一次。 - Teemu
我嵌套事件是因为我需要实时计算字符串长度(不通过回车换行),并且我在使用ctrl,shift和alt等特殊键时遇到了问题。 - M.Gro
好的,我读到了有关输入属性的一些内容,还有一个问题。 为什么willValidate DOM属性是只读的,我无法编辑此值。 如果有更改此值的方法,请告诉我如何操作。 - M.Gro
显示剩余3条评论
1个回答

1
根据W3 input type="number" specificationtype="number"保留用于浮点数
具体来说,以下行描述了您遇到的错误:

值净化算法如下:如果元素的值不是有效的浮点数,则将其设置为空字符串。

因此,在您的代码中,您正在将输入值设置为不是浮点数的内容:
e.target.value = e.target.value.replace(/[^\d]/g, '').replace(/(.{3})/g, '$1 - ').trim();

作为“-”字符被视为“错误输入”,浏览器遵循规范并将值设为空字符串。
要解决此问题,您应该使用type =“tel”,它接受任何有效的电话号码作为输入。
<input type="tel" name="phone" value="" />

这将使现代移动浏览器显示数字键盘布局(例如 type="number")。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接