将 data-title 属性添加到数据表中的 <td>

Joh*_* H. 0 javascript datatable jquery

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

<td data-title="Fruit">Apple</td>
<td data-title="Good or bad">They are delicious</td>
Run Code Online (Sandbox Code Playgroud)

等等...

我目前有这个

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

    } );
});
Run Code Online (Sandbox Code Playgroud)

我的返回 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"
  ]
 ]
}
Run Code Online (Sandbox Code Playgroud)

Ash*_*lam 5

您可以使用数据表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");
            });
        }
    });
});
Run Code Online (Sandbox Code Playgroud)