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

如何在Pug中将动态添加的<tr>数据置于表格首行?

解决Pug表格动态数据置于首行的问题

当前你的代码按records数组原有顺序遍历渲染,新添加的数据若放在数组末尾,自然会显示在表格底部。要让新数据出现在首行,有两种简单可行的方式:

方式一:在Pug中反转遍历顺序

直接在遍历环节调用数组的reverse()方法,让数组从后往前遍历,最后添加的元素会被优先渲染,从而显示在表格顶部。同时调整序号计算逻辑,避免序号颠倒:

<tbody>
  if records.length 
    each record, index in records.reverse()
      - const sl = records.length - index, id = record._id.toString();
      tr(class="data record" data-id= id)
        th(scope="row") #{sl}
        td(class="name") #{record.studentName}
        td(class="subject") #{record.subject}
        td(class="theory") #{record.theory}
        td(class="practical") #{record.practical}
        td(class="total") #{record.total}
        td
          a(href="#" class="editBttn") Edit
        td
          a(href="#" class="delBttn") Delete
  else
    tr(class="data no-record")
      td(colspan="8") No records are available...
</tbody>

records.reverse()反转了数组的遍历顺序,sl = records.length - index则保证序号依然从1开始递增,和数据的逻辑顺序匹配。如果不需要保留原有序号逻辑,也可以直接用index + 1,但此时序号会与原始数组顺序相反。

方式二:在后端插入数据到数组开头

如果不想修改Pug模板的遍历逻辑,可以在后端处理数据时,将新添加的记录直接插入到records数组的开头(比如用JavaScript的unshift()方法),这样模板按原顺序遍历就能让新数据显示在首行,序号计算也无需调整。

内容的提问来源于stack exchange,提问作者Avilash Chak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:25:37