如何使用jQuery获取,解析和汇总表的所有tds? [英] how do I get, parse and sum all the tds' of a table with jQuery?

查看:58
本文介绍了如何使用jQuery获取,解析和汇总表的所有tds?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ID为#stock-hotdogs"的表,其中最后一列始终是".subtotal"类的.小计始终使用以下格式:$ 99.00.因此,我需要知道的是如何获取所有这些td的数字,求和并将它们存储在变量中.应该怎么走?

I have a table with an id "#stock-hotdogs" where the last column is always of the class ".subtotal". The subtotal is always on this format: $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. What should be the way to go?

推荐答案

您可以这样做:

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);
});

在这里我不使用parseFloat,因为人们不应该将浮点值用于财务计算(四舍五入误差).将分数值转换为美元应该是微不足道的:)

I don't use parseFloat here because one should not use float values for financial computations (rounding error). Should be trivial to convert the cent values to dollars :)

这篇关于如何使用jQuery获取,解析和汇总表的所有tds?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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