jQuery多个运行总计
0我正在使用jQuery来计算多个文本框上的运行总计。 刚刚找到了关于如何在几天前开始工作的精彩回应,但现在我遇到了另一个问题。 使用一个选择器时,GetTotal的总计将完美计算。 但是,当我包含第二个选择器时,总计开始相互冲突,并且不再正确计算。 我一直在寻找解决方案一段时间了,有没有人有任何想法?
这是我目前使用的选择器:
function GetTotal(txtBox) { var total = 0; $('input:text').each(function(index, value) { total += parseInt($(value).val() || 0); }); $("#chkTotal").html(total); }
我的观点使用这些txt框
@Html.TextBox("Field1", String.Empty, new {InputType = "text", id = "field1", onchange = "GetTotal(this)" }) @Html.TextBox("Field2", String.Empty, new {InputType = "text", id = "field2", onchange = "GetTotal(this)" }) Total Checked
现在我正在尝试实现另外两个编辑器字段的选择器…
function GetTotal1(txtBox) { var total1 = 0; $('input:text').each(function (index, value) { total1 += parseInt($(value).val() || 0); }); $("#disTotal").html(total1); }
视图:
@Html.TextBox("Field3", String.Empty, new {InputType = "text", id = "field3", onchange = "GetTotal1(this)" }) @Html.TextBox("Field4", String.Empty, new {InputType = "text", id = "field4", onchange = "GetTotal1(this)" }) Total Distributed
在两个总和上使用不同的HTML类,例如
@Html.TextBox("Field1", String.Empty, new {@class = "total0", InputType = "text", id = "field1", onchange = "GetTotal(this)" }) @Html.TextBox("Field2", String.Empty, new {@class = "total0", InputType = "text", id = "field2", onchange = "GetTotal(this)" }) Total Checked
@Html.TextBox("Field3", String.Empty, new {@class = "total1", InputType = "text", id = "field3", onchange = "GetTotal1(this)" }) @Html.TextBox("Field4", String.Empty, new {@class = "total1", InputType = "text", id = "field4", onchange = "GetTotal1(this)" }) Total Distributed
使用Javascript:
function GetTotal(txtBox) { var total = 0; $('input:text.total0').each(function(index, value) { total += parseInt($(value).val() || 0); }); $("#chkTotal").html(total); } function GetTotal1(txtBox) { var total1 = 0; $('input:text.total1').each(function (index, value) { total1 += parseInt($(value).val() || 0); }); $("#disTotal").html(total1); }
无论你是否定义了两个不同的函数,你的each()函数都会运行所有输入字段……
$('input:text').each(...
在两个函数中获取所有4个输入字段。
一种方法是为每个周围的div设置一个类,即:
然后在你的function中
$('.group1 input:text').each(function( ...
更有用的方法是使用function参数传递类:
function GetTotal(group) { var total = 0; $('.'+group+' input:text').each(function(index, value) { total += parseInt($(value).val() || 0); }); $("#chkTotal"+group).html(total); }
您需要重命名每个组的总div:
然后将onChange处理程序中的“this”更改为要汇总的每个组。 (group1,group2等……)
onchange = "GetTotal1(group1)"