我跟 html table
结了 . 我想要结合2 duplicate rows
并将重复行中的值相加 .
我的表格示例:
Name Amount
约翰200
约翰300
约翰100
收获400
收获400
预期结果:
Name Amount
约翰600
哈里什800
我尝试使用下面的jquery代码,但它只有两个重复的行,如果超过两个重复的行发生它不合并但它正在添加值并显示重复的行 .
Html Code:
<table>
<tr>
<td>Name</td>
<td>quantity</td>
<td>expired</td>
</tr>
<tr class="row">
<td class="id">A</td>
<td class="val">25</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">A</td>
<td class="val">25</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">A</td>
<td class="val">25</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">A</td>
<td class="val">25</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">B</td>
<td class="val">100</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">C</td>
<td class="val">35</td>
<td class="date">date</td>
</tr>
<tr class="row">
<td class="id">C</td>
<td class="val">35</td>
<td class="date">date</td>
</tr>
</table>
Jquery Code:
var first_row = '<tr class="row"><td class="id">NULL</td></tr>';
var rowCount = 0;
var rowSum = 0;
$.each($('.row'), function (index, curRow) {
if ($(first_row).find('.id').text() != $(curRow).find('.id').text()) {
if (rowCount > 1) {
$(first_row).find('.val').text(rowSum);
$(first_row).find('.val').css('background-color','silver');
for (i = 0; i < rowCount; i++) {
$(first_row).next('.row').find('.val').remove();
$(first_row).next('.row').find('.date').remove();
$(first_row).next('.row').find('.id').remove();
}
}
first_row = $(curRow);
rowSum = 0;
rowCount = 0;
}
rowSum += parseInt($(curRow).find('.val').text());
rowCount += 1;
});
if (rowCount > 1) {
$(first_row).find('.val').text(rowSum);
$(first_row).find('.val').css('background-color','silver');
for (i = 0; i < rowCount; i++) {
$(first_row).next('.row').find('.val').remove();
$(first_row).next('.row').find('.date').remove();
$(first_row).next('.row').find('.id').remove();
}
}
Result:
Name quantity expired
100日期
25日期
25日期
B 100日期
C 70日期
我想在名称列中所有记录应该是 distinct
和要汇总的数量 .
请在这件事上给予我帮助
2 回答
使用jQuery .nextAll()和.filter()的另一种方法
试试这个: