如何在jQuery数据表中动态显示列标题 [英] How to display the column headers dynamically in jquery data table
问题描述
我有以下代码,用于在数据表中显示具有属性和值的对象数组.但是这里列标题是硬编码的,如下面的html代码所示.如何根据输入数据集使其动态化?
I have the below code for displaying array of objects having property and a value in a data table. But here the column headers are hardcoded as seen in my below html code. How can I make it dynamic based on the input dataset?
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>
推荐答案
假定dataSet中对象的结构不变,则可以使用第一个对象在DataTable声明外部构建json对象.如果对象的结构不一致,则可以调整$ .each结构内部的逻辑以处理该问题.
Assuming the structure of the objects in the dataSet does not change, you could use the first object to build the json object external to the DataTable declaration. If the objects are not of a consistent structure, then you can tweak the logic inside the $.each structure to handle that.
这是一个快速的技巧:
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中的所有静态表内容
You should also consider removing all the static table content in your HTML like this
<table id="example" class="display" cellspacing="0" width="100%"></table>
这是jsFiddle https://jsfiddle.net/z4t1po8o/18/
Here's the jsFiddle https://jsfiddle.net/z4t1po8o/18/
玩得开心.
这篇关于如何在jQuery数据表中动态显示列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!