Firestore按日期区间查询订单仅显示1条,相关JS代码问题排查
问题根因
- 重复使用唯一id
due:HTML规范要求id全局唯一,你初始清空的是外层id为due的容器,但每个订单的模板里给tbody也设置了id="due",后续调用document.getElementById("due")会匹配到最新插入的tbody元素,新订单内容会被错误插入到上一个订单的表格内部,最终仅显示最后一条订单数据。 - 商品循环逻辑错误:写死循环100次,当订单商品数组
items长度不足100时会触发下标越界报错,终止代码执行,导致后续订单无法渲染。 - 频繁操作DOM:每次拼接都直接修改innerHTML,会触发多次DOM重绘,性能差且容易出现渲染异常。
修正后代码
function showData() { let startdate = Date.parse(document.getElementById('startdate').value); let enddate = Date.parse(document.getElementById('enddate').value); const start = startdate; const end = enddate; // 先声明变量存储所有待渲染的HTML内容 let htmlStr = ''; firebase .firestore() .collection("orders") .where('order_datetime', '>=', start) .where('order_datetime', '<=', end) .get() .then((docs) => { docs.forEach((doc) => { if(doc.data().verified == 1){ // 拼接当前订单的头部和表格结构,移除tbody的重复id htmlStr += ` ${doc.data().productname} <div class="table-responsive"> <table class="table table-striped table-borderless border-0 border-b-2 brc-default-l1"> <thead class="bg-none bgc-default-tp1"> <tr class="text-white"> <th class="opacity-2">#</th> <th>Description</th> <th>Qty</th> <th>Unit Price</th> <th width="140">Amount</th> </tr> </thead> <tbody class="text-95 text-secondary-d3"> `; // 遍历当前订单的商品数组,避免硬编码100次 const items = doc.data().items; for (let i = 0; i < items.length; i++) { htmlStr += ` <tr> <td>${i+1}</td> <td>${items[i].productname}</td> <td>${items[i].price}</td> <td class="text-95">$10</td> <td class="text-secondary-d2">$20</td> </tr> `; } // 拼接当前订单的表格闭合标签 htmlStr += ` </tbody> </table> </div> `; } }); // 所有内容拼接完成后一次性赋值到外层容器 document.getElementById("due").innerHTML = htmlStr; }); }
额外优化说明
- 把序号从
i改成了i+1,符合日常表格从1开始计数的使用习惯 - 所有内容拼接完成后再一次性赋值给DOM,减少重绘次数提升渲染性能
- 移除了tbody的重复id,避免DOM选择逻辑混乱
内容的提问来源于stack exchange,提问作者Barcode Payment System
相关产品推荐
相关产品推荐

