Jquery表总和

时间:2014-04-22 07:44:38

标签: javascript jquery html

每次点击" +"我都会尝试创建行。按钮并对每一列求和。我可以创建列。 但没有行。

这是我的代码:

$(document).ready(function () {
    $("#tabla").click(function () {
        $("tr").find("td:last").before('<td><input type="text" value="0"></td>');
        $("tr:last").after('<td><input type="text" value="1"></td>');
        $("input").each(function () {
            $(this).keyup(function () {
                newSum.call(this);

            });
        });
    });
});


function newSum() {
    var sum = 0;
    var thisRow = $(this).closest('tr');

    var total = 0;

    $(thisRow).find("td:not(.total) input").each(function () {

        sum += parseInt(this.value);
    });
    $(thisRow).find(".total").html(sum);

    $('.total').each(function () {

        total += parseInt($(this).html());
    });
}

http://jsfiddle.net/YQ7LQ/

提前致谢。

2 个答案:

答案 0 :(得分:0)

添加了$(document).on('keyup','input',newSum);上调用的行和列总和 Example

答案 1 :(得分:0)

我终于解决了这个问题。

以下是代码:

    //Sum the Rows.
    $('#sum_table tr:not(.totalCol) input:text').bind('keyup change', function() {
    var $table = $(this).closest('table');
    var total = 0;
    var thisNumber = $(this).attr('class').match(/(\d+)/)[1];

    $table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
        total += parseInt(this.value);
    });

    $table.find('.totalCol td:nth-child('+thisNumber+')').html(total);
});

以下是完整代码:

DEMO