jQuery 是一个快速、简洁的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。在用户筛选表格时同步计算合计,可以通过以下步骤实现:
以下是一个简单的示例,展示如何在用户筛选表格时同步计算合计:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Filter and Sum Calculation</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="filterInput" placeholder="Filter by name...">
<table id="dataTable">
<thead>
<tr>
<th>Name</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr><td>Item A</td><td>100</td></tr>
<tr><td>Item B</td><td>200</td></tr>
<tr><td>Item C</td><td>300</td></tr>
<!-- More rows as needed -->
</tbody>
</table>
<div>Total: <span id="total">600</span></div>
<script>
$(document).ready(function() {
function calculateSum() {
let sum = 0;
$('#dataTable tbody tr:visible').each(function() {
sum += parseInt($(this).find('td:nth-child(2)').text(), 10);
});
$('#total').text(sum);
}
$('#filterInput').on('input', function() {
const filterValue = $(this).val().toLowerCase();
$('#dataTable tbody tr').each(function() {
const name = $(this).find('td:first-child').text().toLowerCase();
if (name.indexOf(filterValue) > -1) {
$(this).show();
} else {
$(this).hide();
}
});
calculateSum();
});
// Initial sum calculation
calculateSum();
});
</script>
</body>
</html>
calculateSum()
: 计算当前可见行的金额总和。input
事件到输入框,每当用户输入时,根据输入值过滤表格行并重新计算合计。通过这种方式,可以有效地在用户筛选表格时实时更新合计值,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云