至于你的代码,在你的代码中改变这些东西
所以我有一个非常简单的脚本,我正在编写一个计算器,以便客户可以看到服务的成本,然后根据对文本输入的更改更新结果。 问题是在第一次绕过后,它停止正确计算值。来了,帮忙领略。
<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>
试试这段代码
$(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. 比较 id 而不是值,这样更安全。
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);
});
});