DataTable-使值可排序

时间:2018-08-20 13:42:38

标签: javascript datatables

我正在使用datatables创建表格。

在我的最小可行示例下面查找:

jQuery(document).ready(($) => {
  function loadHardware() {

    var results = {
      "profRigHardware": [{
          "unique_id": "us-sdfasdfsad",
          "title": "Product1",
          "permalink": "http://test.com/computer-hardware/product1/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product1.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "61.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product2",
          "permalink": "http://test.com/computer-hardware/product2/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product2.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "161.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product3",
          "permalink": "http://test.com/computer-hardware/product3/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product3.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-6.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product4",
          "permalink": "http://test.com/computer-hardware/product4/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product4.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-116.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product5",
          "permalink": "http://test.com/computer-hardware/product5/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product5.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-0.06",
        }
      ]
    };
    const rentabilityHtml = function(daily_netProfit) {
      if (daily_netProfit < 0) {
        return `<div style="color:red;"><b>$${daily_netProfit}/day</b></div>`
      } else {
        return `<div style="color:green;"><b>$${daily_netProfit}/day</b></div>`
      }
    }
    //transform data set
    let dataSet = results.profRigHardware.map((item, i) => [
      `<img src="${ item.smallImg }" alt="${ item.title }" height="42" width="42"> 
         <a href="${item.permalink}" target="_blank">
            ${item.title}
             </a>`,
      `${ rentabilityHtml(parseFloat(item.daily_netProfit)) }`,
    ])

    //remove spinner
    $(".loading").remove()

    $('#allHardwareOverview').DataTable({
      data: dataSet,
      destroy: true,
      iDisplayLength: 25,
      responsive: true,
      "bInfo": false,
      "order": [
        [1, 'desc']
      ],
      columns: [{
          title: "Model"
        },
        {
          title: "Profitability"
        }
      ],
      "initComplete": function(settings, json) {
        $('#datatablediv').css('opacity', 1);
      }
    });
  }
  // init
  loadHardware();
});
<link href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.18/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap4.min.js"></script>

<div class="tab-pane fade show active" id="all" role="tabpanel" aria-labelledby="all-tab">
  <div class="table-responsive overflow-x:auto;">
    <table id="allHardwareOverview" style="width:100%; float: left;" class="table table-bordered"></table>
  </div>
</div>

如您所见,我的数据表未正确排序我的获利能力值。

正确的顺序应如下所示:

| Model     | Profitability     |
|---------- |---------------    |
| Product2  | $161.06/day       |
| Product1  | $61.06/day        |
| Product5  | $-0.06/day        |
| Product3  | $-6.06/day        |
| Product4  | $-116.06/day      |

如您所见,订单由获利性列创建。

任何建议为何我的表os排序不正确?

感谢您的答复!

2 个答案:

答案 0 :(得分:1)

您可以将渲染功能添加到Profitability列中,然后将数据转换为HTML,将dataSet的定义更改为:

let dataSet = results.profRigHardware.map((item, i) => [
  `<img src="${ item.smallImg }" alt="${ item.title }" height="42" width="42"> 
         <a href="${item.permalink}" target="_blank">
            ${item.title}
             </a>`,
  parseFloat(item.daily_netProfit), // add the element as the number it is
])

,然后将rowCallback函数添加到您的数据表中以更改列的html:

$('#allHardwareOverview').dataTable({
  ...
  rowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
    $('td:eq(1)', nRow).html(rentabilityHtml($('td:eq(1)', nRow).html()));
  }

});

或者全部:

$(document).ready(($) => {
  function loadHardware() {

    var results = {
      "profRigHardware": [{
          "unique_id": "us-sdfasdfsad",
          "title": "Product1",
          "permalink": "http://test.com/computer-hardware/product1/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product1.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "61.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product2",
          "permalink": "http://test.com/computer-hardware/product2/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product2.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "161.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product3",
          "permalink": "http://test.com/computer-hardware/product3/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product3.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-6.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product4",
          "permalink": "http://test.com/computer-hardware/product4/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product4.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-116.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product5",
          "permalink": "http://test.com/computer-hardware/product5/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product5.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-0.06",
        }
      ]
    };
    const rentabilityHtml = function(daily_netProfit) {
      if (daily_netProfit < 0) {
        return `<div style="color:red;"><b>$${daily_netProfit}/day</b></div>`
      } else {
        return `<div style="color:green;"><b>$${daily_netProfit}/day</b></div>`
      }
    }
    //transform data set
    let dataSet = results.profRigHardware.map((item, i) => [
      `<img src="${ item.smallImg }" alt="${ item.title }" height="42" width="42"> 
         <a href="${item.permalink}" target="_blank">
            ${item.title}
             </a>`,
      //`${ rentabilityHtml(parseFloat(item.daily_netProfit)) }`,
      parseFloat(item.daily_netProfit)
    ])

    //remove spinner
    $(".loading").remove()


    $('#allHardwareOverview').dataTable({
      data: dataSet,
      destroy: true,
      iDisplayLength: 25,
      responsive: true,
      "bInfo": false,
      "order": [
        [1, 'desc']
      ],
      columns: [{
          title: "Model"
        },
        {
          title: "Profitability"
        }
      ],
      "initComplete": function(settings, json) {
        $('#datatablediv').css('opacity', 1);
      },
      rowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        $('td:eq(1)', nRow).html(rentabilityHtml($('td:eq(1)', nRow).html()));
      }
    });
  }
  // init
  loadHardware();
});
<link href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.18/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap4.min.js"></script>

<div class="tab-pane fade show active" id="all" role="tabpanel" aria-labelledby="all-tab">
  <div class="table-responsive overflow-x:auto;">
    <table id="allHardwareOverview" style="width:100%; float: left;" class="table table-bordered"></table>
  </div>
</div>

答案 1 :(得分:1)

我可以看到您正在尝试按第二列进行订购

"order": [
        [1, 'desc']
      ],

但是,第二列是作为字符串而不是数字添加到dataSet的,因此,当您通过第二列进行排序时,数据将按字符串而不是数字进行排序。

如果您对dataSet转换进行如下调整

//transform data set
let dataSet = results.profRigHardware.map((item, i) => [
  `<img src="${ item.smallImg }" alt="${ item.title }" height="42" width="42"> 
     <a href="${item.permalink}" target="_blank">
        ${item.title}
         </a>`,
  //`${ rentabilityHtml(parseFloat(item.daily_netProfit)) }`,
  parseFloat(item.daily_netProfit)
])

您将看到排序正确。

请参阅Codepen中的示例。 https://codepen.io/ji_in_coding/pen/JajXJw?editors=1010