为什么这个带数字输入的函数实际上并不适用于输入类型:数字?

时间:2014-07-04 07:36:21

标签: javascript jquery validation input numbers

$('input').on('keyup',function(){
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

来自:https://stackoverflow.com/a/891816/622813

我使用<input type="number">

进行测试后

当我输入类似1234a的内容时,值空白

但是,当我输入<input type="text">1234a

时,1234没有<input type="tel">

想知道为什么?

演示: http://jsfiddle.net/PV2fQ/


更新:

{{1}}这项工作很好...... http://jsfiddle.net/PV2fQ/10/ 为什么?

1 个答案:

答案 0 :(得分:1)

如果您在替换语句之前执行了console.log(this.value);,则会看到对于非数字输入<input type="number">本身会获得一个空白值,即this.value = '';

这似乎是此输入类型的内部实现。

另一种选择:http://jsfiddle.net/PV2fQ/12/

$('input').keypress(function (e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        return false;
    }
});