简体   繁体   English

简单的 JavaScript 数学没有意义

[英]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()"> &nbsp; % of Beer Drinkers<br> <input type="number" id="winePerc" value="30" onkeyup="calculator2()"> &nbsp; % of Wine Drinkers<br> <input type="number" id="liquorPerc" onkeyup="calculator2()"> &nbsp; % of Liquor Drinkers<br> </div> </div>

Two things:两件事情:

  1. Case is significant.案例很重要。 If you declare the variable bee , you can't read it with Bee .如果声明变量bee ,则无法使用Bee读取它。

  2. .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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM