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

如何在jQuery DataTable中对每行qty、price列执行乘法等数学运算

DataTable 行内字段运算实现方案

一、现有代码问题修复

你当前的代码存在两处基础错误需要先调整:

  • JSON 数据集里存在多余的尾逗号,且qty、price字段部分为字符串类型,计算前需要先转换为数值类型
  • 列配置的结构嵌套错误,total列的配置被错误放在了price列的配置内部

二、基础乘法运算实现

不需要提前在数据源里定义multiplication字段,直接通过columns.render方法读取当前行的两个字段计算即可:

// 先修复数据集,注意去掉多余逗号
const dataSet = [
  {
    "qty": "2",
    "price": 1
  }, 
  {
    "qty": "3",
    "price": "5"
  }, 
  {
    "qty": "3",
    "price": "4"
  }
]

var table = $('#example').DataTable({
  data: dataSet,
  columns: [
    {
      title: "qty",
      data: "qty",
      render: function(data, type, row) {
        return `<input type="number" value="${data}" class="qty-input">`;
      }
    },
    {
      title: "price",
      data: "price",
      render: function(data, type, row) {
        return `<input type="number" value="${data}" class="price-input">`;
      }
    },
    {
      title: "total",
      // 不需要绑定data字段,直接计算
      render: function(data, type, row) {
        // 转成数字再计算,避免字符串拼接问题
        const qty = Number(row.qty)
        const price = Number(row.price)
        // 计算结果保留2位小数,可根据需求调整
        return (qty * price).toFixed(2)
      }
    }
  ]
})

三、输入修改后实时更新运算结果

如果需要支持修改price或者qty的输入框后,自动更新对应行的total值,添加事件监听即可:

// 监听数量、价格输入框变化
$('#example').on('input', '.price-input, .qty-input', function() {
  const $td = $(this).closest('td')
  const $tr = $td.closest('tr')
  const cell = table.cell($td)
  const rowData = table.row($tr).data()
  // 更新行数据
  rowData[cell.data()] = $(this).val()
  // 重绘行,自动触发total的重新计算
  table.row($tr).invalidate().draw()
})

四、拓展其他数学运算

把计算逻辑抽成公共工具函数,需要用的时候直接在render里调用即可,示例:

// 公共运算函数
const calcUtils = {
  // 乘法
  multiply: (a, b) => Number(a) * Number(b),
  // 加法
  add: (a, b) => Number(a) + Number(b),
  // 除法,除数为0时返回0
  divide: (a, b) => Number(b) === 0 ? 0 : (Number(a) / Number(b)).toFixed(2),
  // 求差值
  subtract: (a, b) => Number(a) - Number(b)
}

// 列配置里直接调用即可,比如新增单价计算列
columns: [
  // ...其他列配置
  {
    title: "校验单价",
    render: (data, type, row) => calcUtils.divide(row.total, row.qty)
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:30:04