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

表格sum函数仅首行生效,如何实现每行独立计算?

解决表格每行独立运行sum函数的问题

你的sum函数只对首行生效,核心原因是代码里用了#num1、#sum这类ID选择器——ID在页面中是唯一标识,只会匹配到第一行的对应元素。要实现每行独立计算,按以下方式修改即可:

步骤1:调整HTML结构

把每行输入框和结果框的ID改为类名,确保每行对应元素用相同类名标记,示例结构如下:

<tr>
  <td><input type="number" class="num1"></td>
  <td><input type="number" class="num2"></td>
  <td><input type="number" class="num3"></td>
  <td><input type="number" class="sum" readonly></td>
  <td><input type="number" class="sum1" readonly></td>
</tr>
<tr>
  <!-- 第二行复用相同类名 -->
  <td><input type="number" class="num1"></td>
  <td><input type="number" class="num2"></td>
  <td><input type="number" class="num3"></td>
  <td><input type="number" class="sum" readonly></td>
  <td><input type="number" class="sum1" readonly></td>
</tr>

步骤2:修改JavaScript逻辑

监听类选择器的输入事件,计算时仅针对当前输入框所在的行操作:

$(function() {
  // 监听所有类为num1、num2、num3的输入框
  $(".num1, .num2, .num3").on("keydown keyup", sum);
  
  function sum() {
    // 定位当前输入框所在的表格行
    const $currentRow = $(this).closest("tr");
    
    // 仅在当前行内获取数值,空值或非数字默认取0
    const num1 = Number($currentRow.find(".num1").val()) || 0;
    const num2 = Number($currentRow.find(".num2").val()) || 0;
    const num3 = Number($currentRow.find(".num3").val()) || 0;
    
    // 计算并赋值给当前行的结果框
    const total = num1 * num2;
    $currentRow.find(".sum").val(total);
    
    const discountedTotal = total - (total * (num3 / 100));
    $currentRow.find(".sum1").val(discountedTotal);
  }
});

关键改动说明

  • 用类选择器替代ID选择器,打破唯一匹配限制,让每行元素都能被选中
  • 通过$(this).closest("tr")锁定当前操作的行,确保计算仅作用于该行元素
  • 添加|| 0处理空输入或非数字内容,避免出现NaN计算结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:55:29