javascript - 使用jquery向表中添加行

标签 javascript jquery

我有一个像这样的 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/

相关文章:

javascript - 从文本框输入并添加到列表中不起作用

javascript - 单击而不是悬停访问无限下拉菜单

javascript - 创建我自己的类似于暗黑破坏神 3 旅程追踪器的 Web 应用程序时遇到问题

javascript - 需要帮助简化代码

javascript - 表格列宽度匹配

javascript - 我怎样才能真正捕获 JavaScript 中花括号之间的内容?

javascript - 移动端完全不同的 View

javascript - 需要简单的 JavaScript HTML DOM 函数的帮助

Javascript从另一个网站的源代码中查找html元素的问题

javascript - 排序 "day" "week" "month"和 "year"