You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery计算商品价格总和、销量总和及最终总金额?

原有代码问题

  • 提取了价格数值存到findProject变量后未使用,错误读取了普通div不存在的this.value属性,导致价格统计失效
  • 没有增加销量统计逻辑,无法得到总销量Value2

修正实现

循环遍历每个商品节点,分别提取价格、销量的有效数值,累加后计算乘积即可得到正确结果,完整代码如下:

// 初始化统计变量
let totalPrice = 0; // Value1:所有商品价格总和
let totalSell = 0;  // Value2:所有商品总销量

jQuery('.data-single').each(function(){
    // 提取单商品价格:去掉$符号转成浮点数
    const price = parseFloat(jQuery(this).find('.data-value').text().replace('$', '').trim());
    // 提取单商品销量:去掉Sales后缀转成整数
    const sell = parseInt(jQuery(this).find('.data-sell').text().replace('Sales', '').trim());
    
    // 校验数值合法后累加
    if (!isNaN(price)) totalPrice += price;
    if (!isNaN(sell)) totalSell += sell;
});

// 计算最终总金额
const finalAmount = totalPrice * totalSell;

// 将结果写入页面对应位置
jQuery('.set-column .total-price').eq(0).text(`Final Amount - Value1 * Value2 : $${finalAmount.toFixed(2)}`);
jQuery('.set-column .total-sell').text(`Total Price - Value1 : $${totalPrice.toFixed(2)}`);
jQuery('.set-column .total-price').eq(1).text(`Total Sell - Value2 : ${totalSell}`);

示例计算结果

你给出的4个商品统计结果如下:

  • 总价格Value1:$181
  • 总销量Value2:1247
  • 最终总金额:$225707

内容的提问来源于stack exchange,提问作者Jignesh Panchal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:42:03