【发布时间】:2015-02-21 01:58:06
【问题描述】:
我的页面中有这样的表格:
<table class="table table-bordered table-striped">
<caption>
<h3>Itens do Estrutural</h3>
<div class="input-group input-group-lg col-md-9">
<span class="input-group-addon">Filtrar:</span>
<input type="text" name="filterbox" id="filterbox" class="form-control" placeholder="Type your search here ..." />
</div><br />
</caption>
<thead>
<tr>
<th>Company</th>
<th>Description</th>
<th>Value</th>
</tr>
<tr class="info">
<td colspan="2" class="text-right">TOTAL:</td>
<td class="total text-right"></td>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td class="text-center">@Html.DisplayFor(modelItem => item.Company)</td>
<td>@Html.DisplayFor(modelItem => item.Description)</td>
<td class="valor text-right">@Html.DisplayFor(modelItem => item.Value)</td>
</tr>
}
</tbody>
<tfoot>
<tr class="info">
<td colspan="2" class="text-right">TOTAL:</td>
<td class="total text-right"></td>
</tr>
</tfoot>
</table>
当文档准备好时,它会计算类别为 valor 的列的总计,并显示在类别为 total 的列的表格的头部和底部.
这个想法是,用户可以在输入文本中输入任何名为 filterbox 的内容来过滤行,因此应该重新计算总数。
此时我可以使用下面的 jQuery 代码过滤行:
$(document).ready(function () {
var $rows = $(".table tbody tr");
var total = 0;
$rows.each(function () {
total += parseFloat($(this).find(".valor").text().replace(/\./g, "").replace(",", "."));
});
$("#filterbox").keyup(function () {
var filtertext = $(this).val();
var regex = new RegExp(filtertext, 'i');
$rows.hide().filter(function () {
return regex.test($(this).text());
}).show();
});
$(".total").html(formataTotal(total.toFixed(2)));
});
function formatTotal(num) {
var parts = num.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
return parts.join(",");
}
我尝试了以下方法来重新计算总数,但没有奏效:
$("#filterbox").keyup(function () {
var filtertext = $(this).val();
var regex = new RegExp(filtertext, 'i');
$rows.hide().filter(function () {
return regex.test($(this).text());
}).each(function () {
total += parseFloat($(".table tbody tr").find(".valor").text().replace(/\./g, "").replace(",", "."));
}).show();
});
我应该怎么做才能对过滤行时重新计算的值求和?
感谢您的关注。 保罗·里卡多·费雷拉
【问题讨论】:
-
重新计算后出现什么错误?
-
嗨,@Arthur Samarcos。没有错误。它只是显示与仍然显示的所有行相同的总数。
-
您得到相同的结果,因为您必须通知脚本仅汇总可见行。尝试使用 "total += parseFloat($(".table tbody tr:visible").find(".valor") etc"
-
嗨,@Arthur Samarcos。我试过你的建议,但没有任何区别。仍然得到相同的结果。谢谢。
标签: jquery