这是因为
我从另一篇文章中获得了这段代码。
Number.prototype.countDecimals = function () {
if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
return this.toString().split(".")[1].length || 0;
}
var x = 23.453453453;
x.countDecimals(); //returns 9 as expected
基本上,它返回给定数字中的小数位数。问题是,我需要从输入中的一个数字中获得这个值:
console.log($('#myinput').val().countDecimals());
但该操作返回:未捕获类型错误:未定义不是函数
如何集成以前的代码来处理输入值(使用jQuery)?谢谢
您在Number
对象的原型中定义了countDecimals
函数,因此它只能在类型为Number
的对象上调用。我还没有对此进行测试,但您可以使用Number($('#myinput').val()).countDecimals()
。
.val()
实际上返回了一个对象:Object [value]
。只需在上面执行parseFloat
即可:
console.log( parseFloat( $('#myinput').val() ).countDecimals() );
它将给出所需的结果,
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type ="text" id="inpVal">
<input type ="button" id="inpBtn" value="click!!!!">
<script>
Number.prototype.countDecimals = function () {
if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
return this.toString().split(".")[1].length || 0;
}
$("#inpBtn").click(function(){
var x = parseFloat($("#inpVal").val()).countDecimals();
alert(x);
});
</script>
</body>
</html>