我是javaScript的新手。我正在构建一个计算器here
我已将输入值存储在变量中,以便最终可以根据输入操作结果以执行计算。现在我只想将所有值加在一起。
但是,它们不是添加,而是连接在一起。我使用parseInt来阻止javascript将数字视为字符串,而typeOf显示它们是数字。
这是我的javascript:
$(document).ready(function() {
var theTerm = $("#theTerm").val();
var theRate = $("#theRate").val();
var thePrice = $("#thePrice").val();
var theTax = $("#theTax").val();
var theDown = $("#theDown").val();
var theTrade = $("#theTrade").val();
var theResult = parseInt(theTerm + theRate + thePrice + theTax + theDown + theTrade, 10);
$("#calculate").click(function(){
alert(theResult);
alert(typeof(theResult));
});
});
和HTML:
<div id="calculator">
<span id="calculatorHeader">Monthly Payment Calculator</span>
<table style="margin:0 auto;">
<tr>
<td style="width:40px;">Term
<input id="theTerm" size="5" value="7" name="term" style="width:35px" />
</td>
<td style="width:40px;">Rate(%)
<input id="theRate" size="5" value="7" name="apr" style="width:35px" />
</td>
<td style="width:55px;">Price($)
<input id="thePrice" size="6" maxlength="7" name="price" style="width:50px" value="7" />
</td>
<td style="width:40px;">Tax(%)
<input id="theTax" size="4" maxlength="7" name="tax" style="width:35px" value="7" />
</td>
<td style="width:40px;">Down($)
<input id="theDown" size="5" maxlength="7" name="downPmt" style="width:35px" value="7" />
</td>
<td style="width:40px;">Trade($)
<input id="theTrade" size="5" maxlength="7" name="trade" style="width:35px" value="7" />
</td>
<td style="width:78px;">Est.Monthly Pmt
<input id="theResult" size="7" maxlength="7" name="result" style="width:75px" value="0" />
</td>
</tr>
</table>
<button type="button" id="calculate">Add Boxes!</button>
</div>
答案 0 :(得分:15)
更改行并将parseInt应用于每个obj,如下所示
var theResult = parseInt(theTerm) + parseInt(theRate) + parseInt(thePrice) + parseInt(theTax) + parseInt(theDown) + parseInt(theTrade);
答案 1 :(得分:5)
您可以将数字乘以parseInt
,而不是使用1
。它更快更容易地隐藏数据类型。
$(document).ready(function () {
var theTerm = $("#theTerm").val() * 1;
var theRate = $("#theRate").val() * 1;
var thePrice = $("#thePrice").val() * 1;
var theTax = $("#theTax").val() * 1;
var theDown = $("#theDown").val() * 1;
var theTrade = $("#theTrade").val() * 1;
var theResult = theTerm + theRate + thePrice + theTax + theDown + theTrade;
$("#calculate").click(function () {
alert(theResult);
alert(typeof (theResult));
});
});
JSFiddle:http://jsfiddle.net/RqzPk/14/
答案 2 :(得分:3)
稍微整理一下代码并避免重复:
$(document).ready(function() {
$("#calculate").click(function(){
var inputs = $("input"), theResult = 0; // `inputs` is the list of all input elements
for(var i = 0;i < inputs.length; i++) // iterate over all inputs
// parse their value, in base 10, and add to the theResult
theResult += parseInt(inputs[i].value, 10);
alert(theResult); // 42
});
});
答案 3 :(得分:1)
您将字符串与+
连接起来,然后将该连接结果转换为int。
您希望在添加之前转换为整数。类似的东西:
var theTerm = parseInt($("#theTerm").val(), 10);
...
var theResult = theTerm + theRate + thePrice + theTax + theDown + theTrade;
答案 4 :(得分:1)