如何在jquery数据表中动态显示列标题

Bru*_*uce 3 jquery datatables

我有以下代码用于显示具有属性和数据表中的值的对象数组.但是这里的列标题是硬编码的,如下面的html代码所示.如何根据输入数据集使其动态化?

 var dataSet = [{
  "Latitude": 18.00,
  "Longitude": 23.00,
  "Name": "Pune"
}, {
  "Latitude": 14.00,
  "Longitude": 24.00,
  "Name": "Mumbai"
}, {
  "Latitude": 34.004654,
  "Longitude": -4.005465,
  "Name": "Delhi"
},{
  "Latitude": 23.004564,
  "Longitude": 23.007897,
  "Name": "Jaipur"
}];
$(document).ready(function() {
    $('#example').DataTable( {
        data: dataSet,
        "columns": [
            { "data": "Name" ,"title":"Custom Name"},
            { "data": "Latitude" },
            { "data": "Longitude" },

        ]
    } );
} );




<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Latitude</th>
                <th>Longitude</th>

            </tr>
        </thead>

    </table>
Run Code Online (Sandbox Code Playgroud)

nan*_*ech 10

假设dataSet中对象的结构没有改变,您可以使用第一个对象来构建DataTable声明外部的json对象.如果对象的结构不一致,那么你可以调整$ .each结构中的逻辑来处理它.

这是一个快速的黑客:

var dataSet = [{
  "Latitude": 18.00,
  "Longitude": 23.00,
  "Name": "Pune"
}, {
  "Latitude": 14.00,
  "Longitude": 24.00,
  "Name": "Mumbai"
}, {
  "Latitude": 34.004654,
  "Longitude": -4.005465,
  "Name": "Delhi"
}, {
  "Latitude": 23.004564,
  "Longitude": 23.007897,
  "Name": "Jaipur"
}];

var my_columns = [];

$.each( dataSet[0], function( key, value ) {
        var my_item = {};
        my_item.data = key;
        my_item.title = key;
        my_columns.push(my_item);
});

$(document).ready(function() {
  $('#example').DataTable({
    data: dataSet,
    "columns": my_columns
  });
});
Run Code Online (Sandbox Code Playgroud)

您还应该考虑删除HTML中的所有静态表内容

<table id="example" class="display" cellspacing="0" width="100%"></table>
Run Code Online (Sandbox Code Playgroud)

这是jsFiddle https://jsfiddle.net/z4t1po8o/18/

玩得开心.