2016-09-22 81 views
0

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

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> 

回答

4

假设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 
    }); 
}); 

你也应该考虑在你的HTML删除所有静态表的内容是这样

<table id="example" class="display" cellspacing="0" width="100%"></table> 

这里的的jsfiddle https://jsfiddle.net/z4t1po8o/18/

有乐趣。

相关问题