如何使用jQuery嵌套foreach循环生成产品表格 解决数据undefined问题
渲染出现undefined问题的原因与修正方案
核心问题定位
- 字段名错配:内层循环调用了不存在的
data.retailsTable字段,接口实际返回的产品数据集字段为productTable,遍历不存在的undefined值时会直接触发脚本报错,中断渲染流程 $.each语法使用错误:jQuery的$.each遍历数组时,回调函数的参数顺序是(索引值, 当前遍历元素),原代码的回调仅接收了1个参数,这个参数实际是遍历的数字索引(0、1、2),并非产品数据对象,因此读取属性时必然返回undefined- 表格结构逻辑错误:原代码仅预留了1个数据行
product_item,但需要为yearly、today两个统计周期分别生成独立行,而非把所有内容塞进同一行 - 表格标签位置不规范:原代码把表头行
product_title放在了<tbody>外部,不符合HTML表格的语法规范,容易引发渲染异常
修正后可直接运行的代码
调整后的HTML结构
<table> <thead> <tr id="product_title"></tr> </thead> <tbody id="product_table_body"> </tbody> </table>
修正后的脚本逻辑
fetch('http://127.0.0.1:8000/api/productTable') .then(response => response.json()) .then(data => { // 生成产品列表表头 $('#product_title').append('<th>Period</th>'); data.productTable.forEach(product => { $('#product_title').append(`<th>${product.name}</th>`); }); // 按统计周期生成对应数据行 $.each(['yearly', 'today'], function(periodIndex, periodName) { // 创建当前周期的独立行 const $currentRow = $('<tr></tr>'); $currentRow.append(`<td>${periodName}</td>`); // 遍历所有产品,匹配对应周期的数值 $.each(data.productTable, function(productIndex, productItem) { $currentRow.append(`<td>${productItem[periodName]}</td>`); }); // 将组装完成的行插入表格主体 $('#product_table_body').append($currentRow); }); });
最终渲染效果
代码执行后会生成完全匹配需求的统计表格:
| Period | Apple | Banana | Mangoes |
|---|---|---|---|
| yearly | 21 | 45 | 95 |
| today | 10 | 14 | 5 |
内容的提问来源于stack exchange,提问作者Beginner Coder
相关产品推荐
相关产品推荐

