【问题标题】:Jquery Datatable sort not working with html elementsJquery Datatable 排序不适用于 html 元素
【发布时间】:2019-04-05 03:27:30
【问题描述】:

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

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

附上示例代码here(jsfiddle)

【问题讨论】:

标签: javascript jquery datatables


【解决方案1】:

我之前在一些项目中遇到过这个问题,使用mRender() 而不是fnCreatedCell()render 函数接收 type 作为第二个参数,您可以从该参数中检测渲染是否为 '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>

【讨论】:

  • 解决了我的问题!这次真是万分感谢!当涉及到 HTML 逗号或 HTML 十进制数字格式时,Jquery Datatable 是有问题的。它真的很有帮助。 @Shidersz
猜你喜欢
  • 2020-05-22
  • 1970-01-01
  • 2012-08-27
  • 2021-09-28
  • 2021-07-09
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多