1

所以我有一个非常简单的脚本,我正在编写一个计算器,这样客户就可以看到服务的成本,然后根据文本输入的更改更新结果。问题是在第一次绕过后它会停止正确计算值。在这里,帮助赞赏。

<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>
4

1 回答 1

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/


至于您的代码,请在您的代码中更改这些内容

一种。比较 ids 而不是值,这样更安全。
湾。删除第二个更改功能。根本不需要。

$(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);
    });
});​
于 2012-04-23T02:47:04.290 回答