layui table合计行默认统计全部数据,需在done回调中动态计算当前页平均值:通过curr和config.limit确定切片范围,从table.cache提取当前页数据并reduce求均值,再手动更新footer对应td内容。
合计行默认只支持 sum/avg/count,但不区分“当前页”和“全部数据”
layui 的 table.render 合计行(done 回调中调用 table.cache + footer 手动渲染)默认统计的是全部加载数据,不是当前页。如果你启用了分页且开启了 page: true,直接用 data: table.cache['your-id'] 拿到的是全量缓存,不是当前页可见行。
关键点在于:Layui 不提供“当前页数据子集”的现成 API,必须自己从 table.config 和 table.cache 中提取当前页的原始数据。
实操建议:
- 在
done回调里,通过curr(当前页码)、limit(每页条数)计算当前页数据在全量缓存中的起止索引 - 从
table.cache['your-id']中切片取出当前页数据(注意:这是原始 JSON 数组,不是 DOM 行) - 对切片后的数组做
reduce计算平均值,保留合适小数位(如toFixed(2)) - 用
layui.$('.layui-table-footer td[data-field="xxx"]').html(...)或重绘footer区域
如何在 done 回调中安全获取当前页数据子集
done 回调参数为 (res, curr, count),其中 curr 是当前页码,count 是总条数,但缺 limit —— 它藏在 table.config['your-id'].limit 里。别硬写死 limit 值,要动态读取。
示例代码片段(放在 done 内):
const ins = table.get('your-table-id');
const config = ins.config;
const limit = config.limit || 10;
const start = (curr - 1) * limit;
const end = start + limit;
const currentPageData = table.cache['your-table-id'].slice(start, end);
const avgPrice = currentPageData.length
? (currentPageData.reduce((a, b) => a + (parseFloat(b.price) || 0), 0) / currentPageData.length).toFixed(2)
: '--';
layui.$('.layui-table-footer td[data-field="price"]').html(`平均:${avgPrice}`);
注意:table.cache 是实时更新的,但仅当使用 url + parseData 或 data 静态加载时才可靠;若用 initSort 或前端排序,需确保排序后 cache 已同步(Layui v2.8+ 通常没问题,v2.7- 可能需加 setTimeout 延迟执行)。
避免 footer 被重复渲染或错位的三个细节
Layui 的 footer 是表格 DOM 的一部分,手动修改 td 内容容易被后续重绘覆盖(比如切换页码、触发排序)。必须确保操作时机正确,且避免选择器污染。
- 每次
done都要重新定位td[data-field="xxx"],不要缓存 jQuery 对象(DOM 可能重建) - 如果表格有固定列(
fixed: 'left'),footer 的结构会拆成多个table,此时.layui-table-footer td可能匹配不到,应改用layui.$('.layui-table-box .layui-table-footer td[data-field="xxx"]') - 平均值字段若为数字类型,建议统一转
parseFloat并判空,否则NaN会污染整个计算(NaN + number === NaN)
服务端分页下 avg 计算逻辑必须由前端承担
服务端分页时,后端只返回当前页数据,table.cache 就是当前页数据 —— 此时看似简单,但陷阱在于:很多人误以为 table.cache 是全量,其实它只存了最近一次接口返回的数据(除非你手动合并)。所以服务端分页反而更安全,无需切片。
但要注意:parseData 必须正确返回 data 字段,否则 table.cache 为空。验证方式:在 done 里打印 console.log(table.cache['your-id']),确认长度等于当前页条数。
此时计算平均值可简化为:
const cache = table.cache['your-table-id']; const avg = cache.length ? (cache.reduce((s, d) => s + (parseFloat(d.score) || 0), 0) / cache.length).toFixed(1) : '—';
复杂点在于混合场景:前端分页 + 列过滤 + 排序后求当前页均值 —— 这时 table.cache 是原始数据,必须用 table.getData()(Layui v2.8+)或自行维护过滤后数组,不能依赖默认 cache。











