js报错Uncaught TypeError: $(...).text().toFixed is not a function
发布日期: 2024-03-12
FontSize: 【小 中 大】

浏览器控制台报错Uncaught TypeError: $(...).text().toFixed is not a function(未捕获的类型错误:$(…).text().toFixed不是函数)。
is not a function,这应该是一个错误的报错,toFixed函数是js函数,而不是js自定义函数。造成这个报错的原因是$(...).text()获取的内容是文本类型而不是数字类型。
关于toFixed函数,详见:https://www.w3school.com.cn/jsref/jsref_tofixed.asp,当调用该方法的对象不是 Number 时抛出的异常。
将上面获取的文本类型强制更改为数字类型:
parseFloat($(...).text()).toFixed(2);/*parseFloat 解析字符串并返回浮点数*/
或者:
parseInt($(...).text()).toFixed(2);/*parseInt 解析字符串并返回整数*/
例如,将id值为number的元素里面的数字保留两位小数:
$("#number").text(parseFloat($("#number").text()).toFixed(2));
测试:
<div id="num1">1000</div>
<div id="num2">2000</div>
<script type="text/javascript" src="https://z.lichil.com/vendor/js/jquery-1.11.1.min.js"></script>
<script type="module">
$(function() {
console.log(parseInt($("#num1").text()).toFixed(2));
console.log($("#num1").text().toFixed(2));
});
</script>
您会发现,在控制台输出了1000.00,以及