简体   繁体   English

如何使用 jQuery 获取、解析和汇总表的所有 td?

[英]how do I get, parse and sum all the tds' of a table with jQuery?

I have a table with an id "#stock-hotdogs" where the last column is always of the class ".subtotal".我有一个 ID 为“#stock-hotdogs”的表,其中最后一列始终是 class“.subtotal”。 The subtotal is always on this format: $99.00.小计始终采用这种格式:$99.00。 So what I need to know is how to get the numbers of all those td's, sum them and store them in a variable.所以我需要知道的是如何获取所有这些 td 的数字,对它们求和并将它们存储在一个变量中。 What should be the way to go? go应该怎么走?

You could do:你可以这样做:

var cents_total = 0;

$('#stock-hotdogs .subtotal').each(function() {
    var value = $.trim($(this).text());
    var parts = value.substr(1).split('.');
    cents_total += +parts[0] * 100 + (+parts[1] || 0);
});

I don't use parseFloat here because one should not use float values for financial computations (rounding error).我在这里不使用parseFloat ,因为不应该将浮点值用于财务计算(舍入误差)。 Should be trivial to convert the cent values to dollars:)将美分值转换为美元应该很简单:)

var inputs = $('td.subtotal', '#stock-hotdogs').find('input');

var total = 0;

$(inputs).each(function() {
    total += parseFloat( $(this).val().replace(/[^\d\.]+/g, ''));
});

Here is a live working example OR是一个现场工作示例或

A second version that isn't using input elements...不使用输入元素的第二个版本......

$('#totalbtn').click(function() {
    var total = 0;
    $('td.subtotal', '#stock-hotdogs').each(function() {
        total += parseFloat( $(this).text().replace(/[^\d\.]+/g, ''));
    });

});

HERE is an example for this...是一个例子......

var subTotals = $('#stock-hotdogs td.subtotal');
var sum = 0;

subTotals.each(function() {
    sum += parseFloat($(this).text().substr(1));
});

alert(sum);

Working Example: http://jsfiddle.net/FishBasketGordo/f5V9P/工作示例: http://jsfiddle.net/FishBasketGordo/f5V9P/

Use:利用:

var total=0;
$('#stock-hotdogs .subtotal').text(function(i,v){
    total+=parseFloat(v.substr(1));
});

alert('total: $'+total.toFixed(2));

Take a look at the JQuery Calculation plugin: it lets you specify which fields to sum using jQuery selectors.查看JQuery 计算插件:它允许您使用 jQuery 选择器指定要求和的字段。 Using it you would do something like this:使用它你会做这样的事情:

$("#stock-hotdogs").find("td.subtotal").sum();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM