2012-04-23 77 views
1

所以我写了一个非常简单的脚本作为计算器,以便客户端可以看到服务将花费多少钱,然后根据对文本输入的更改更新结果。问题是在第一次出现后停止正确计算值。在这里,它是令人满意的。简单的计算器jquery脚本

<script> 
$(function(){ 


var one=0; 
var two=0; 
var three=0; 
$("input:text").change(function(){ 
if($(this).val() == $('#first').val()) 
{ 
one = parseInt($(this).val()); 



} 
else if($(this).val() == $('#second').val()){ 

two = parseInt($(this).val()); 

} 
else if($(this).val() == $('#third').val()){ 

three = parseInt($(this).val()); 

} 

}); 


$('input:text').change(function(){ 

$('#result').text(one+two+three); 


}); 


}); 


</script> 

和形式:

<div id="container"> 
<form action="something.html" id="subit"> 
<label for="first">put numbers</label><input type="text" id="first"/> 
<label for="second">more numbers</label><input type="text" id="second" value="0"/> 
<label for="third">and more numbers</label><input type="text" id="third" value="0"/> 
<input type="submit" /> 
</form> 
<div id="result"></> 
</div> 
+0

您在第一次运行后更改'change()'函数,对吗? – Marc 2012-04-23 02:34:42

+0

Marc,你是什么意思?基本上我首先要做的是:将值分配给变量,然后根据添加这些值更新结果。 – 2012-04-23 02:40:19

+0

问题是“count”在第一轮添加后熄灭。添加val 1,2,3,然后尝试再次更改,结果是错误的。 – 2012-04-23 02:41:53

回答

1

试试这个代码

$(document).ready(function() { 
    var textboxes = $("#container input:text"); 
    textboxes.on("keyup", function() { 
     var amt = 0; 
     textboxes.each(function() { 
      amt += +$(this).val(); 
     }); 
     $("#result").html(amt); 
    }); 
});​ 

工作小提琴:http://jsfiddle.net/naveen/87p53/


至于你的代码,在代码

改变这些东西

a。比较ids而不是值,它更安全。 b。删除第二个更改功能。根本不需要。

$(function() { 
    var one = 0; 
    var two = 0; 
    var three = 0; 
    $("input:text").change(function() { 
     if (this.id == "first") { 
      one = parseInt($(this).val()); 
     } 
     else if (this.id == "second") { 
      two = parseInt($(this).val()); 
     } 
     else if (this.id == "third") { 
      three = parseInt($(this).val()); 
     } 
     $('#result').html(one + two + three); 
    }); 
});​ 
+0

Naveen太棒了!非常简洁。 – 2012-04-23 02:53:02

+0

任何机会,你知道为什么我写的代码不起作用? – 2012-04-23 02:57:53

+0

再次感谢,总是乐于学习。 – 2012-04-23 03:27:08