使用服务器端处理时的自定义渲染

时间:2015-04-27 14:36:59

标签: javascript datatables jquery-datatables

我想知道在收到ajax响应后是否可以修改表的呈现。这似乎与此处描述的render函数有关:https://www.datatables.net/manual/orthogonal-data

我的服务器返回数据

{
    "name":       
                       {
                        id: "123456",
                        value: "Tiger Nixon"
                        }
}

我想在每个名称单元格中添加名称data-attribute的ID或td的ID,并希望为每个单元格添加.on( "click", handler )

这可能吗?

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以在返回的数据中使用DT_RowDataDT_RowAttr(需要DataTables 1.10.5或更高版本)参数,将属性分配给<tr>元素,稍后您可以在点击处理程序中检索这些属性,请参阅手册中的Server-side processing章节。

或者您可以使用render方法,但可能效果不佳。我假设您的name列的索引为0,并且您要设置data-id属性。

var table = $('#example').DataTable({
   "columnDefs": [{
      "data": "name.value",
      "targets": 0,
      "render": function ( data, type, full, meta ) {
         if(type === 'display'){
            $('#example').DataTable().cell(meta.row, meta.col).nodes().to$().attr('data-id', full['name']['id']);
         }

         return data;
      }
   }]
});

您可以使用以下代码添加点击事件处理程序:

$(document).ready(function(){
    var table = $('#example').DataTable({
       // Define DataTables initialization options here 
    });

    $('#example tbody').on('click', 'td', function(){

       // Use table to access various API function
       //
       // For example:
       // var data_cell = table.cell(this).data();

    });
});

答案 1 :(得分:0)

使用columns.createdCell功能可以实现这一点。

对于旧的DataTables版本,Gyrocode的答案是正确的。