bootstrap_table自定义排序方法

公司老项目使用的是bootstrap框架,表格使用的是bootstrap-table。当前有个需求,需要按照自定义方法来排序。

比如要求,某些数据固定排在头部,其他的则按照对应字段排序。

最新的bootstrap-table中有customSort方法。

解释:The custom sort function is executed instead of the built-in sort function, takes three parameters: 

  • sortName: the sort name.
  • sortOrder: the sort order.
  • data: the rows data.

但是,项目中使用的是1.9.1 没有此方法。

于是曲线救国,采用prepend方法,插入要固定的数据。

初始化table之后,和每次点击排序名称的时候,添加两行代码:

$(this.table).bootstrapTable("refreshOptions", {data: data}) // data, 正常排序的数据
$(this.table).bootstrapTable("prepend", topFixed); // topFixed, 要固定在顶部的数据

这样就可以把需要固定显示在顶部的数据固定了,后面的数据依然按照列名对用字段排序。

customSort用法:

首先看一下对比效果:

默认排序:

 

 customSort:

 

直接上代码:添加customSort有两种方法,一种是添加data-custom-sort属性,另一种是配置项

    <table id="basic_table" data-custom-sort="customSort" ></table>


    $("#basic_table").bootstrapTable({
      data: dataT,
      customSort: customSort,
      columns: [
        {
          field: 'id',
          title: 'ID'
        },
        {
          field: 'name',
          title: '姓名',
          sortable: true,
        },
        {
          field: 'code',
          title: '编号'
        }
      ]
    });

customSort 方法接收三个参数:

    // 自定义排序方法,排序名称,排序方法(升序/降序),数据列表
    function customSort(sortName, sortOrder, data) {
      data.sort(function(a,b) {
        let aa = a[sortName].toString().replace(/[^\d]/g, ''); // 非数字替换成空字符串
        let bb = b[sortName].toString().replace(/[^\d]/g, '');
        if(sortOrder == 'desc') {
          return aa-bb;
        } else {
          return bb-aa;
        }
      })
      
    }

 

posted @ 2020-03-30 16:33  我的故事没编好  阅读(5442)  评论(0编辑  收藏  举报