[英]Simple JavaScript math not making sense
I feel like I'm a novice again.感觉自己又变成新手了。 I thought I was long past these problems.
我以为我早就解决了这些问题。 below is a simple script with two function neither of which work.
下面是一个简单的脚本,有两个功能,但都不起作用。 What am I missing.
我错过了什么。 Any help appreciated.
任何帮助表示赞赏。
function calculator() { var bee = document.getElementById("beerPerc").value; var win = document.getElementById("winePerc").value; var liq = 100 - (bee + win); document.getElementById("liquorPerc").value = liq; } function calculator2() { document.getElementById("liquorPerc").value = parseInt(100 - (document.getElementById("beerPerc").value + document.getElementById("winePerc").value)) }
<div id="calcArea"> <div> <input type="number" id="beerPerc" value="50" onkeyup="calculator2()"> % of Beer Drinkers<br> <input type="number" id="winePerc" value="30" onkeyup="calculator2()"> % of Wine Drinkers<br> <input type="number" id="liquorPerc" onkeyup="calculator2()"> % of Liquor Drinkers<br> </div> </div>
Two things:两件事情:
Case is significant.案例很重要。 If you declare the variable
bee
, you can't read it with Bee
.如果声明变量
bee
,则无法使用Bee
读取它。
.value
is always a string. .value
始终是一个字符串。 You need to convert the strings to numbers:您需要将字符串转换为数字:
var bee = Number(document.getElementById("beerPerc").value);
If you don't do this, +
will perform string concatenation, not addition.如果不这样做,
+
将执行字符串连接,而不是加法。
You don't need to call parseInt()
on the result of a numeric calculation, that's always a number.您不需要对数值计算的结果调用
parseInt()
,它始终是一个数字。
function calculator2() {
document.getElementById("liquorPerc").value = 100 - (parseInt(document.getElementById("beerPerc").value, 10) + parseInt(document.getElementById("winePerc").value, 10)))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.