如何通过列索引指定Bootstrap Table的默认排序列
解决方案
可以通过列索引指定默认排序列,以下是两种可直接落地的实现方式:
方案1:模板渲染阶段直接配置(推荐)
该方案无需额外编写JS逻辑,性能最优,直接在Jinja2模板循环渲染列时,给目标索引的列配置排序属性即可。
示例为默认对第2列(列索引从0开始计数,对应索引为1)做升序排序,修改后的代码如下:
<table id="table_example" class="table table-striped" data-toggle="table"> <thead> <tr> {% for idx, col in enumerate(column_names) %} <!-- 给目标索引列添加data-sorted属性开启默认排序,如需降序可加data-sort-order="desc" --> <th data-field="col_{{ idx }}" {% if idx == 1 %} data-sorted="true" data-sort-order="asc" {% endif %}>{{col}}</th> {% endfor %} </tr> </thead> <tbody> {% for row in row_data %} <tr> {% for col, row_ in zip(column_names, row) %} <td>{{row_}}</td> {% endfor %} </tr> {% endfor %} </tbody> </table>
如果你的模板环境没有提前注册enumerate全局函数,也可以直接使用Jinja2内置的loop.index0变量获取当前列的索引,对应判断条件改为{% if loop.index0 == 1 %}即可。
方案2:前端JS动态配置
如果无需修改后端模板渲染逻辑,可以通过JS在Bootstrap Table初始化完成后,主动触发指定索引列的排序:
$(function() { $('#table_example').on('post-body.bs.table', function () { // 自定义配置:要排序的列索引(从0开始计数)、排序规则asc/desc const targetColumnIndex = 2 const sortOrder = 'desc' // 获取对应列的字段名 const sortName = $(this).bootstrapTable('getOptions').columns[0][targetColumnIndex].field // 执行排序 $(this).bootstrapTable('sortBy', { sortName: sortName, sortOrder: sortOrder }) // 解绑事件,避免后续表格操作重复触发排序 $(this).off('post-body.bs.table') }) })
内容的提问来源于stack exchange,提问作者Tomek
相关产品推荐
相关产品推荐

