JavaScript处理循环生成的HTML表格时计算High与Low列差值出错如何解决
问题根源
- HTML 规范要求
id属性全局唯一,你在循环生成每一行的<td>时,重复使用了high、low、ratio等同名id,导致document.getElementById()永远只能匹配到页面里第一个出现的对应id元素,所以每次计算拿到的都是第一行的数值,自然所有输出结果都一致。
修复方案
推荐两种可行的修复方式,按需选择即可:
方案1:模板渲染阶段直接计算(性能最优)
不需要额外编写JavaScript,直接在模板渲染表格时就计算出差值填充到对应单元格,修改ratio列的代码即可:
<td id='ratio'>{{y|access_dictionary:'ohlc'|access_dictionary:'high'|add:"-"|add:y|access_dictionary:'ohlc'|access_dictionary:'low'}}</td>
如果模板自带的过滤器不支持减法运算,自定义一个简单的减法过滤器即可实现。
方案2:统一用JavaScript遍历计算
删除循环中插入的script代码,把重复的id改为可复用的class,最后在表格加载完成后统一遍历所有行计算差值:
第一步:修改循环内的单元格属性
{% for x,y in info.items %} <tr> <td scope="row">{{x|split}}</td> <td class='open'>{{y|access_dictionary:'ohlc'|access_dictionary:'open'}}</td> <td class='high'>{{y|access_dictionary:'ohlc'|access_dictionary:'high'}}</td> <td class='low'>{{y|access_dictionary:'ohlc'|access_dictionary:'low'}}</td> <td>{{y|access_dictionary:'ohlc'|access_dictionary:'close'}}</td> <td>{{y|access_dictionary:'volume'}}</td> <td class='buyquantity'>{{y|access_dictionary:'buy_quantity'}}</td> <td class='sellquantity'>{{y|access_dictionary:'sell_quantity'}}</td> <td class='ratio'></td> </tr> {% endfor %}
第二步:在</table>标签后添加全局计算脚本
document.addEventListener('DOMContentLoaded', function() { // 获取所有表格行 const rows = document.querySelectorAll('#people tr'); rows.forEach(row => { // 取当前行的高低价转成数字 const high = Number(row.querySelector('.high').textContent); const low = Number(row.querySelector('.low').textContent); // 计算差值写入对应列,toFixed参数可按需调整保留小数位数 row.querySelector('.ratio').textContent = (high - low).toFixed(2); }) })
内容的提问来源于stack exchange,提问作者amar gupta
相关产品推荐
相关产品推荐

