我有一个像这样的 html 表格:
Group Amount
x 3
x 1
test 2
test 5
但我想要这个:
Group Amount
x 3
x 1
sum x 4
test 2
test 5
sum test 7
我已经可以在索引处添加一行:
$('.mytable > tbody > tr').eq(i-1).after(html);
但是我怎样才能用jquery获取索引和总和呢?
最佳答案
这将为所有 future 的组执行您需要的操作,并且值可以按任何顺序排列,但我强烈建议您在第一次获取信息时在服务器上执行所有这些操作...
var groups = {};
// get the sums of all the groups in the table, and the index of the last row of each
$(".mytable tbody tr").each(function(i) {
var group = $(this).find("td").eq(0).text();
var value = parseInt($(this).find("td").eq(1).text(), 10);
if (groups.hasOwnProperty(group)) {
groups[group].sum += value;
}
else {
groups[group] = {
sum: value
};
}
groups[group].index = i;
});
// convert the group information into an array so it can be sorted...
var groupArray = [];
for(var group in groups) {
groups[group].name = group;
groupArray.push(groups[group]);
}
// sort the groups in reverse index order
groupArray = groupArray.sort(function(a, b) {
return b.index - a.index;
});
// parse the groups of values and add them to the table, after the final row of each group
for (var i = 0, l = groupArray.length; i < l; i++) {
$(".mytable tbody tr").eq(groupArray[i].index).after("<tr><td>Sum " + groupArray[i].name + "</td><td>" + groupArray[i].sum + "</td></tr>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="mytable">
<thead>
<tr>
<th>Group</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>x</td>
<td>3</td>
</tr>
<tr>
<td>x</td>
<td>1</td>
</tr>
<tr>
<td>test</td>
<td>2</td>
</tr>
<tr>
<td>test</td>
<td>5</td>
</tr>
</tbody>
</table>
关于javascript - 使用jquery向表中添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32566402/