javascript - 为什么在 Firefox 中输入逗号时此正则表达式会清除所有字符?

标签 javascript regex html

我想使用数字类型输入字段,但如果输入了美元符号(对于非 Chrome 浏览器),则去掉美元符号。

但是使用下面的代码,如果我输入 300 或 300.. 等等,它会清除我所有的输入。

这是怎么回事?

jQuery( 'input' ).keyup( function( ) {
  this.value = this.value.replace(/\$/g, '*');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">

最佳答案

那是因为,当你设置 value , value sanitization algorithm被调用。对于 number inputs ,

The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.

由于 300, 不是有效数字,输入被清除。

然后,不是替换字符,更好的方法是阻止它们被写入:

jQuery('input').keydown(function(e) {
  if(e.key == '$' || e.which == 52 || e.keyCode == 52) e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">

关于javascript - 为什么在 Firefox 中输入逗号时此正则表达式会清除所有字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34010837/

相关文章:

javascript - 如何在 node.js 中重定向

javascript - 需要帮助创建图像上传表单

python - 正则表达式用多行Python匹配和替换字符串

html - 宽度和最小宽度的使用

javascript - 检查是否切换为 true addClass else if not removeClass

javascript - 社交媒体按钮不会出现在 BlogSpot 上

regex - 有没有更有效的方法来使用 grep 进行拼字游戏搜索?

regex - 如何使用 Perl 正则表达式删除换行符?

javascript - 让 js 过滤器工作以显示菜单

javascript - 更改 ID 加载的背景