jQuery sum表格单元格 [英] jQuery sum table cells

查看:76
本文介绍了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);
});

小提琴演示

这篇关于jQuery sum表格单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆