使用Javascript实现动态增删行的行值与列值计算功能
解决方案
问题原因
- 原有事件直接绑定在
.Participants元素上,仅页面初始加载时已存在的元素能触发事件,后续动态新增的行元素没有绑定计算事件,导致新增行修改后无响应 - 原有计算逻辑仅统计了参与人数总和,未实现单条培训价值计算和总价值汇总逻辑
- 动态新增的行中「总培训价值」输入框缺少
TotalAmount类标识,无法统一选中进行批量计算
修复步骤
1. 修改动态新增行配置
给动态生成的「总培训价值」输入框添加 TotalAmount 类,方便后续统一选中计算。
2. 替换原有计算逻辑为事件委托模式
使用事件委托绑定计算事件,让后续新增的元素也能自动触发计算逻辑,同时实现单行培训价值计算、全量总价值汇总两个需求。
完整修改后代码
//Dynamic Add Delete Rows $(document).ready(function() { var i = 1; $("#add_row").click(function() { $('#addr' + i).html("<td>" + (i + 1) + "</td><td><select class='form-control' required name='topic[" + i + "]'><option selected disabled value=''>Select Topic</option><option value='1'>Topic 1</option></select></td><td><input name='alloc_trainig[" + i + "]' type='text' placeholder='Allocated Trainings' class='form-control input-md'></td><td><input name='add_traing[" + i + "]' type='text' placeholder='Additional Trainings (if Any)' class='form-control'></td><td><input name='no_patycpnt[" + i + "]' type='text' placeholder='No. of Participants' class='Participants form-control input-md'></td><td><input name='prosd_days[" + i + "]' type='text' placeholder='Proposed Days' class='form-control input-md'></td><td><input name='subsify_per_patrcpnt[" + i + "]' type='text' placeholder='Subsidy Per Participant' class='Subsidy form-control input-md'></td><td><input type='text' name='total_value[" + i + "]' placeholder='Total Value' readonly class='TotalAmount form-control'/></td>"); $('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>'); i++; }); $("#delete_row").click(function() { if (i > 1) { $("#addr" + (i - 1)).html(''); i--; // 删除行后重新触发计算更新总金额 $('.Participants:first').trigger('change'); } }); // 全量计算逻辑:修改参与人数、每人补贴时都会触发 $(document).on('change', '.Participants, .Subsidy', function() { let totalAll = 0; // 遍历所有有效行计算 $('#tab_logic tbody tr').each(function() { const $row = $(this); // 跳过空占位行 if ($row.find('.Participants').length === 0) return; // 取值非数字默认按0计算 const people = parseFloat($row.find('.Participants').val()) || 0; const subsidy = parseFloat($row.find('.Subsidy').val()) || 0; // 计算单行总价值,保留2位小数,不需要可以去掉toFixed const rowTotal = people * subsidy; $row.find('.TotalAmount').val(rowTotal.toFixed(2)); // 累加总金额 totalAll += rowTotal; }); // 赋值总分配值字段 $('#contrctval').val(totalAll.toFixed(2)); }); });
内容的提问来源于stack exchange,提问作者Hassan
相关产品推荐
相关产品推荐

