我想使用数字类型输入字段,但如果输入了美元符号(对于非 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/