jquery - 计算乘积的总和和总计

标签 jquery

我有一组产品,每行都有数量、价格和总和,如下图所示:

enter image description here

我想用jquery自动计算每行的总和以及最后的总数,而不退出页面。

我对 jquery 没有丰富的经验。

我怎样才能做到这一点?

非常感谢。

最佳答案

这是我认为你想做的事情的 fiddle :

http://jsfiddle.net/maniator/qEy3L/

JS:

function getTotal(){
    var total = 0;
    $('.price').each(function(){
        total += parseFloat(this.innerHTML)
    });
    $('#total').text(total);
}

getTotal();

HTML:

<table>
    <thead>
        <tr>
            <th>QTY</th>
            <th>PRICE</th>
            <th>SUM</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>2</td>
            <td>1.25</td>
            <td class='price'>2.50</td>
        </tr>
        <tr>
            <td>3</td>
            <td>2.10</td>
            <td class='price'>6.30</td>
        </tr>
        <tr>
            <td>5</td>
            <td>10.50</td>
            <td class='price'>52.50</td>
        </tr>
        <tr>
            <td colspan='2'>Total</td>
            <td id='total'></td>
        </tr>
    </tbody>
</table>

更新:

这是一个可更新数量的版本:http://jsfiddle.net/maniator/qEy3L/5/

JS:

function getTotal(){
    var total = 0;
    $('.sum').each(function(){
        total += parseFloat(this.innerHTML)
    });
    $('#total').text(total);
}

getTotal();

$('.qty').keyup(function(){
    var parent = $(this).parents('tr');
    var price = $('.price', parent);
    var sum = $('.sum', parent);
    var value = parseInt(this.value) * parseFloat(price.get(0).innerHTML||0);
    sum.text(value);
    getTotal();
})

HTML:

<table>
    <thead>
        <tr>
            <th>QTY</th>
            <th>PRICE</th>
            <th>SUM</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input class='qty' size='1'/></td>
            <td class='price'>1.25</td>
            <td class='sum'>0</td>
        </tr>
        <tr>
            <td><input class='qty' size='1'/></td>
            <td class='price'>2.10</td>
            <td class='sum'>0</td>
        </tr>
        <tr>
            <td><input class='qty' size='1'/></td>
            <td class='price'>10.50</td>
            <td class='sum'>0</td>
        </tr>
        <tr>
            <td colspan='2'>Total</td>
            <td id='total'></td>
        </tr>
    </tbody>
</table>

关于jquery - 计算乘积的总和和总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6412376/

相关文章:

javascript - 表单验证消息不显示

javascript - jQuery.ajax 未捕获语法错误 : Unexpected identifier

javascript - 从数组javascript创建数组

html - 等待 jQuery ajax 响应完成页面更新,然后再允许另一个 ajax 调用

jquery - 如何通过表单元素传递 json

javascript - 按下按钮递增数据然后推送到多维数组

javascript - ajax后重新构建iframe

jquery - 如何使用 jQuery/JavaScript 解析 JSON 数据?

php - jquery ajax提交表单上传图片

javascript - 迭代匹配元素来控制自定义光滑轮播