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;
        }
      })
      
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM