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

如何使用jQuery获取div内容值并按指定规则完成数值计算

实现方案

你之前直接读取整行文本的方式会把所有字段的内容拼接为一个字符串,无法单独提取,你可以通过匹配每行内对应类名的节点单独取值计算,参考代码如下:

核心计算函数

function calcularTotais() {
  // 初始化三个统计变量
  let totalQuantity = 0;
  let totalWeight = 0;
  let totalCubage = 0;

  // 遍历所有行,slice(1)用于跳过第一行表头
  $('.rowtabela').slice(1).each(function() {
    const $currentRow = $(this);
    // 提取当前行各字段的数值,转为浮点型,为空时默认取0避免计算错误
    const qty = parseFloat($currentRow.find('.v_volumes').text().trim()) || 0;
    const height = parseFloat($currentRow.find('.v_altura').text().trim()) || 0;
    const width = parseFloat($currentRow.find('.v_largura').text().trim()) || 0;
    const depth = parseFloat($currentRow.find('.v_profundidade').text().trim()) || 0;
    const weight = parseFloat($currentRow.find('.v_peso').text().trim()) || 0;

    // 按需求累加对应值
    totalQuantity += qty;
    totalWeight += qty * weight;
    totalCubage += (height * width * depth) * qty;
  });

  // 将计算结果赋值到页面对应的只读输入框
  $('#volumes').val(totalQuantity);
  // 可根据业务需求调整保留的小数位数
  $('#peso_total').val(totalWeight.toFixed(2));
  $('#cubagem').val(totalCubage.toFixed(4));
}

触发时机

因为你的表格是动态生成的,只需要在两个场景调用这个函数即可实时更新统计值:

  • 新增一行数据的逻辑执行完成后
  • 点击删除按钮删除行的remover函数逻辑执行完成后

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:15:05