我在这段代码中有一个小错误,请帮助我。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0,
maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
<script type="text/javascript">
function calc() {
"use strict";
var price = document.getElementById('price').value;
var res = (price / 100 * 5 + 20) + price;
var show = document.getElementById('show').value = Math.floor(res);
}
</script>
</body>
</html>
例如:在输入中写100结果是10025,我需要125
发布于 2018-07-02 07:31:27
这是因为您尝试将字符串添加到数字中。您需要将price
转换为如下所示的数字:
var price = parseFloat(document.getElementById('price').value);
// Or like this :
var price = Number(document.getElementById('price').value);
// Or like this :
var price = document.getElementById('price').value * 1;
显示十进制数的完整示例:
var priceElement = document.getElementById('price');
var showElement = document.getElementById('show');
function calc() {
var price = parseFloat(priceElement.value, 10);
var result = (price / 100 * 5 + 20) + price;
showElement.innerHTML = result.toFixed(2);
}
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
发布于 2018-07-02 08:08:42
可以,价格的值为字符串,请将其转换为数字。
我不认为你的"document.getElementById('show').value“有用。
并且没有使用变量show。
res的公式有点复杂--参见var v1。
也许你会发现使用console.log在调试中很有用。
<html>
<body>
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
<script type="text/javascript">
"use strict";
function calc() {
var price = 1*document.getElementById('price').value;
console.log("price", price);
var res = (price / 100 * 5 + 20) + price;
console.log("res", res);
document.getElementById('show').innerHTML = Math.floor(res);
var v1 = price*1.05 + 20;
console.log("v1", v1);
document.getElementById('show').innerHTML += ", " + v1;
}
</script>
</body>
</html>
https://stackoverflow.com/questions/51127697
复制相似问题