使用 HTML5 数据属性的多列排序

Multi-column ordering using HTML5 data- attribute

我正在尝试将 jQuery DataTables 中的多列排序用作 HTML5 data- 属性。这可能吗?

我已经试过了:

<th>Firstname</th>
<th data-orderData="[ 3, 2 ]">Lastname</th>

但它没有用,虽然这个工作正常:

<th data-orderable="false" data-searchable="false">Edit</th>

我试过将其声明为 table data- 属性,如下所示:

<table id="myTable" data-columnDefs="[ {'targets': [ 5 ], 'orderData': [ 5, 3, 2 ]} ]">

但这也没有用,虽然这个工作正常:

<table id="myTable" data-order="[[ 5, 'asc' ], [ 3, 'asc' ], [ 2, 'asc' ]]">

我在官方文档中找不到任何关于使用 HTML5 data- 属性进行多列排序的内容。这甚至可以通过 HTML5 data- 属性来实现吗?

原因

请参阅 HTML5 data-* attributes 页上的注释:

There are two important points to consider when using data-* attributes as initialization options:

  • jQuery will automatically convert from dashed strings to the camel case notation used by DataTables (e.g. use data-page-length for pageLength).
  • If using a string inside the attribute it must be in double quotes (and therefore the attribute as a whole in single quotes). This is another requirement of jQuery's due to the processing of JSON data- data.

解决方案

您需要使用 data-column-defs 而不是 data-columnDefs 并确保您在选项名称中使用 双引号

<table data-column-defs='[ {"targets": [ 3 ], "visible": false} ]' id="example" class="display" cellspacing="0" width="100%">

<table data-column-defs="[ {&quot;targets&quot;: [ 3 ], &quot;visible&quot;: false} ]" id="example" class="display" cellspacing="0" width="100%">

演示

有关代码和演示,请参阅 this jsFiddle