将data-title属性添加到我的数据表中

时间:2016-10-10 15:52:38

标签: javascript jquery datatable

我正在使用datatables为我的所有表提供jquery datatables magic, 我通过向我的td添加数据标题来执行响应表。如何将数据标题添加到我的所有td中,使它们看起来像这样

<td data-title="Fruit">Apple</td>
<td data-title="Good or bad">They are delicious</td>

依旧......

我目前有这个

$(document).ready(function() {
    $('#contacts').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "src/data.php?form_action=get-table",

    } );
});

我的回归json看起来像这样

{
"draw":"1",
"recordsTotal":2,
"recordsFiltered":2,
"data":[
  [
     "Apples",
     "They are delicious",
     "2016-10-10 07:47:12",
     "New entry",
     "1"
  ],
  [
     "Bananas",
     "They are also delicious",
     "2016-10-10 07:47:12",
     "New entry",
     "2"
  ]
 ]
}

1 个答案:

答案 0 :(得分:4)

您可以使用数据表createdRow回调。像这样,

$(document).ready(function() {
    $('#contacts').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "src/data.php?form_action=get-table",
        // Per-row function to iterate cells
        "createdRow": function (row, data, rowIndex) {
            // Per-cell function to do whatever needed with cells
            $.each($('td', row), function (colIndex) {
                // For example, adding data-* attributes to the cell
                $(this).attr('data-title', "your cell title");
            });
        }
    });
});