jQuery sum表格单元格

问题描述:

总和表格单元格

<table>
    <tr>
        <td><input type="text"></td>
        <td><input class="price" type="text" value="100"></td>
        <td><input class="quantity" type="text" value="2"></td>
        <td><input type="text"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input class="price" type="text" value="100"></td>
        <td><input class="quantity" type="text" value="5"></td>
        <td><input type="text"></td>
    </tr>
    <tfoot>
        <tr class="summary">
            <td>Total:</td>
            <td id="total_price"></td>
            <td id="total_quantity"></td>
            <td class="second"></td>
            <td class="third"></td>
        </tr>
    </tfoot>    
</table>


<script>
    $(document).ready(function() {
        var sum = 0;
        var quantity = 0;
        $('.price').each(function() {
            sum += (parseInt($('.price').val()) * parseInt($('.price').val()));
            quantity += parseInt($('.quantity').val();
        });

        $('#total_price').html(sum);
        $('#total_quantity').html(quantity);
    })
</script>

输出必须是:总和:700;总数量:7

Output must be: Total sum: 700; Total quantity: 7

更改 $('。price ') $(this),引用回调中的元素。

Change $('.price') to $(this), to refer the element inside the callback.

$(document).ready(function() {
    var sum = 0;
    var quantity = 0;
    $('.price').each(function() {
        var price = $(this);
        var q = price.closest('tr').find('.quantity').val();
        sum += parseInt(price.val()) * parseInt(q);
        quantity += parseInt(q);
    });

    $('#total_price').html(sum);
    $('#total_quantity').html(quantity);
});

小提琴演示