2011-01-27 75 views
3

如何在Javascript中添加一个简单的整数到另一个整数?Javascript增加整数

我得到NaN作为总值。

<script type="text/javascript"> 
var total = 0; 
document.getElementById("dds1").onkeyup = function() { 
    total = total + parseInt(this.value,10); 
    updateIt(); 

}; 

function updateIt() { 
//tofixed(2) 
    document.getElementById("mySpan").innerHTML = total; 
} 

但是,如果我执行以下操作:

total = parseInt(this.value,10); 

然后总有一个值(整数值)。

+3

你应该使用jQuery ....没有,只是在开玩笑`:D' – 2011-01-27 19:25:09

+1

我怀疑还有更多的代码参与其中。您发布的内容似乎没有任何问题。还有什么改变“总计”? – Pointy 2011-01-27 19:27:02

回答

5

问题是,执行加法读取每个键盘上的输入值。例如,如果用户按BACKSPACE清除输入,则该值将是一个空字符串,这将导致parseInt之后的NaN。一旦你有NaN(在你的total变量中),你就无法摆脱它了。

试试这个:

document.getElementById('dds1').onkeyup = function() { 

    var value = parseInt(this.value, 10); 

    if (!isNaN(value)) { 
     total += value; 
     updateIt();  
    } 

}; 

在这里,你先检查输入值可以解析为一个数字。如果不是,你只是无视它。


做这将是另外一个办法:

document.getElementById('dds1').onkeyup = function() { 
    var value = parseInt(this.value, 10); 

    isNaN(value) && return; 

    total += value; 
    updateIt(); 
}; 

在这里,如果你读的是不能转换成数字的输入值,你可以返回功能完全。

1

这里是JavaScript来添加整数。 好东西就是即使是空白也不会抛出任何错误。

的Javascript

<script language="javascript" type="text/javascript"> 
 

 
    function Add() { 
 
    var a, b, c, d; 
 
    a = parseInt(document.getElementById("txtFirstValue").value); 
 

 
    // 
 
    // If textbox value is null i.e empty, then the below mentioned if condition will 
 
    // come into picture and make the value to '0' to avoid errors. 
 
    // 
 

 
    if (isNaN(a) == true) { a = 0; } 
 
    var b = parseInt(document.getElementById("txtSecondValue").value); 
 

 
    if (isNaN(b) == true) { b = 0; } 
 
    var c = parseInt(document.getElementById("txtThirdValue").value); 
 

 
    if (isNaN(c) == true) { c = 0; } 
 
    var d = parseInt(document.getElementById("txtFourthValue").value); 
 

 
    if (isNaN(d) == true) { d = 0; } 
 
    document.getElementById("txtTotal").value = a + b + c + d; 
 
} 
 
</script> 
 

 
<!-- begin snippet: js hide: false --> 
 

 
HTML
First Value: <asp:TextBox ID="txtFirstValue" runat="server" 
 
         onKeyUp="javascript:Add();"></asp:TextBox> 
 

 
Second Value:<asp:TextBox ID="txtSecondValue" runat="server" 
 
         onKeyUp="javascript:Add();"></asp:TextBox> 
 

 
Third Value:<asp:TextBox ID="txtThirdValue" rrunat="server" 
 
         onKeyUp="javascript:Add();"><asp:TextBox> 
 

 
Fourth Value:<asp:TextBox ID="txtFourthValue" runat="server" 
 
         onKeyUp="javascript:Add();"></asp:TextBox> 
 

 
Total = <asp:TextBox ID="txtTotal" runat="server" MaxLength="20" BackColor="#FFE0C0" 
 
         Enabled="False" Font- Font-Bold="True" Font-Size="X-Large"> 
 
      </asp:TextBox>

从推介:http://www.ittutorials.in/source/javascript/scf4/addition-of-multiple-integers-using-javascript.aspx