如何使用数据表行分组中的数据源创建 link?

How can I create a link using the data source in Datatables Row Grouping?

我正在使用 Datatables 1.10 插件 Jquery 和行分组高级初始化:https://datatables.net/examples/advanced_init/row_grouping.html 我想从数据库添加一个 link 到分组列,在示例中,link 将是 EdinburghLondon

在我使用 column.render: https://datatables.net/reference/option/columns.render 添加 link 之前,它可以正常工作。正如您在代码中看到的那样,我的目标是第 1 列 (working) 并且想要定位第 0 列,即分组的隐藏列 (not working).

第 0 列已隐藏并包含组名。 第 3 列被隐藏并包含 link.

JS代码如下:

$(document).ready(function() {
var dataTable = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax":{
        url :"example.php", // json datasource
        type: "post",  // method  , by default get
            error: function(){  // error handling
              $(".example-error").html("");
              $("#example").append('<tbody class="example-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
              $("#example_processing").css("display","none");
            }
          },

          "columnDefs": [
          { "visible": false, "targets": [ 0, 3] },
          { "width": "50%", "targets": [ 1, 2 ] },
          { "orderable": false, "targets": [ 1, 2 ] },
          { "targets": 1,
          "data": null,
          "render": function ( data ) {
            return '<a href=//'+data[ 3 ]+' target="_blank">'+data[ 1 ]+'</a>';
          }}
          ],

          "order": [[ 0, 'asc' ]],
          "displayLength": 25,
          "drawCallback": function ( settings ) {
            var api = this.api();
            var rows = api.rows( {page:'current'} ).nodes();
            var last = null;

            api.column(0, {page:'current'} ).data().each( function ( group, i ) {
              if ( last !== group ) {
                $(rows).eq( i ).before(
                  '<tr class="group"><td colspan="5">'+group+'</td></tr>'
                  );

                last = group;
              }
            } );
          }
        } );
        } );

谢谢!

SOLUTION

您需要修改drawCallback函数如下图:

api.rows({page:'current'} ).data().each( function ( data, i ) {
   var group = data[0];
   var groupLink = '<a href="' + data[3] + '">' + $('<div>').text(group).html() + '</a>';

   if ( last !== group ) {
      $(rows).eq( i ).before(
         '<tr class="group"><td colspan="5">'+group+'</td></tr>'
      );

      last = group;
   }
});

DEMO

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

NOTES

我还使用了 orderFixed,因此 table 始终按包含组名的列排序(在我的示例中为 2)。