我有一个像这样的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得到索引和总和?
答案 0 :(得分:1)
行索引可以使用表行元素(.rowIndex
)的de $tr[0].rowIndex
属性。
总和,如果元素按组排序,则必须迭代元素:
var group, sum = 0;
$('table tr').each(function () {
var $tr = $(this);
if (!group)
group = $tr.children('td:first-child').text();
sum += parseFloat($tr.children('td:last-child').text());
if ($tr.next().children('td:first-child').text() !== group) {
$tr.after('<tr><td>sum of ' + group + '</td><td>' + sum + '</td></tr>');
sum = 0;
group = null;
}
});
虽然你可以用这个达到预期的效果,但我鼓励你不要这样做。您非常依赖数据和HTML结构。您的代码将变得脆弱,难以维护,并且可能性能较差。
答案 1 :(得分:1)
请试试这个。
_send_bytes
&#13;
var sums = [];
$("table.mytable tbody tr").each(function(index) {
var label = $(this).find("td:first-child").html();
var value = parseInt($(this).find("td:last-child").html());
if (sums.length == 0 || sums[sums.length - 1].label != label)
sums.push({
index: index,
label: label,
sum: value
});
else
sums[sums.length - 1].sum += value;
});
for (var i = 0; i < sums.length; i++)
$('table.mytable > tbody > tr').eq(sums[i].index + i).after("<tr><td>" + sums[i].label + "</td><td>" + sums[i].sum + "</td></tr>");
&#13;
答案 2 :(得分:1)
对于所有未来的群组,这将按照任何顺序为您提供所需的值,但我强烈建议您在首次获取信息时在服务器上执行所有操作....
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>");
}
&#13;
<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>
&#13;