首页 > 解决方案 > Jquery Datatable 排序不适用于 html 元素

问题描述

排序不适用于表格单元格中的 html 元素。

尝试将其添加aoColumnDefs到其中。还要为具有的列指定列数据,'sType': 'html'并且排序似乎不起作用。

此处附上示例代码(jsfiddle)

标签: javascriptjquerydatatables

解决方案


我之前在一些项目中遇到过这个问题,使用mRender()而不是fnCreatedCell(). 该render函数接收 atype作为第二个参数,您可以从该参数中检测渲染是否为'display''sort'其他。因此,如果类型是,'display'您可以返回HTML原始数据,否则返回原始数据。

var data = [
  ["test", [20.2, "green"], "test"],
  ['test1', ['10.2', 'red'], "test"],
  ['test2', ['15.2', 'red'], "test"],
  ['test3', ['0', 'red'], "test"],
  ['test4', ['0.5', 'green'], "test"],
  ['test5', ['1.5', 'green'], "test"],
];  

$(document).ready(function()
{
    $('#data2').DataTable(
    {
      bSort: true,
      aaData: data,
      aaSorting: [[1, 'asc']],
      aoColumnDefs: [
        { 
          bSortable: true,
          sType: "numeric", 
          aTargets: [1],
          mRender: function(data, type)
          {
            if (type !== 'display')
              return data[0];

            return '<label style="color:' + data[1] + '">' + data[0] + '</label>';
          },
        }
      ]
    });    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src=https://cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.9.4/css/jquery.dataTables.css">

<table id="data2" class="">
  <thead>
  <tr>
    <th>col1</th>
    <th>col2</th>
    <th>col3</th>
  </tr>
  </thead>
</table>


推荐阅读