JavaScript的运行总计将错误 [英] javascript running total adding incorrectly
问题描述
大家好,我试图做使用JavaScript找到一个运行总计一个很简单的计算。我似乎失去了一些东西。我也期待通过SO和发现了一些非常相似的场景,但我似乎无法与我自己的code。
Hey everyone I'm trying to do a very simple calculation using javascript to find a running total. I seem to be missing something. I did look through SO and found some very similar scenarios but, I can't seem to relate to my own code.
下面是我使用的calc下我跑步的总脚本。
Here is the script I am using to calc my running total.
var total = 0;
function GetTotal(txtBox) {
total += parseInt(txtBox.value) || 0;
$("#chkTotal").html(total);
}
,这里是从我的观点有些code:
and here is some code from my view:
<div class="editor-field">
@Html.TextBox("FirstDemo", String.Empty, new { id = "firstdemo", onchange = "GetTotal(this)" })
@Html.ValidationMessageFor(model => model.FirstDemo)
</div>
<div>
<h3>Total Checked</h3>
</div>
<div id="chkTotal"></div>
总计算完美,直到一个值在文本框中改变,在这种情况下,任何已在文本框中输入了被再次添加到运行总数。
The total calculates perfectly, until a value is changed in a text box, in which case whatever has been entered in the textbox is added again to the running total.
谁能帮我?
推荐答案
问题是你的总
变量的全球范围内:我想你已经在多个文本字段形成在那里你将其设置为处理 onchage
事件相同的方式。你输入一些第一次,值正确添加到总,但你改变的时刻中的任何文本字段的东西,它再次增加了新的价值。同样,因为总
具有全局范围。
The problem is the global scope of your total
variable: I imagine you have several text fields in the form where you set them up to handle the onchage
event the same way. The first time you enter something, the value is added correctly to total but the moment you change something in any of the text fields, it adds again the new value. Again, because total
has global scope.
您真的应该移动总
本地函数内,并在你感兴趣的投入要素重新解析所有值。
You should really move total
locally inside the function and re-parse all values in the input elements you are interested in.
由于您使用jQuery,你可以做这样的事情,而不是:
Since you are using jquery, you could do something like this instead:
function GetTotal(txtBox) {
var total = 0;
$('input:text').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
下面是一个的jsfiddle 展示给你。
这篇关于JavaScript的运行总计将错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!