我正在尝试学习Javascript并创建一些简单的脚本,我试图为我创建一个运费成本脚本。计算到货物品的运费。除数字格式外,一切正常。我尝试使用toFixed()
方法格式化数字。但它不起作用。我检查了控制台结果是
Uncaught TypeError: undefined is not a function (index):23
calculate (index):23
onclick
这是我的index.php文件:
<html>
<head>
<title>Shipping cost</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="wrapper">
Price : <input type="number" name="price" id="price" />
Pounds : <input type="number" name="pounds" id="pounds" />
<input type="button" value="Calculate" onclick="calculate()" />
</div>
<script type="text/javascript">
function calculate(){
var price = document.getElementById('price').value;
var pounds = document.getElementById('pounds').value;
var rule = parseFloat(price) * 0.04 + parseFloat(pounds) * 7;
var total = price + rule;
var result = total.toFixed(2);
document.write(result);
}
</script>
</body>
</html>
答案 0 :(得分:3)
price
是一个字符串,因此price + rule
也是一个字符串。并且字符串没有toFixed
方法。
如果您想要数字,可以使用unary operator +
。
var price = +document.getElementById('price').value,
pounds = +document.getElementById('pounds').value,
rule = price * 0.04 + pounds * 7,
total = price + rule,
result = total.toFixed(2);