[英]Dynamically create columns / HTML tables using DataTable or plain JQUERY
I have requirement where I need to show data in HTML in following structure 我有需要在以下结构中以HTML显示数据的要求
Region
--------------------------------
outlet1 | outlet2 | outlet3 |
---------------------------------
123 | 323 | 123
233 | 34234 | 23234
Number of outlets are not fixed . 网点数量不固定。 Varibales of my Java Object that will be formed by action and which will be throws as JSON are
我的Java对象的变量将由动作形成并且将作为JSON抛出
DataObject : regionName, outletName, personName, count
list of these DataObjects will be used. 将使用这些DataObject的列表。
How can I draw these using Data Table or plain Jquery. 如何使用数据表或纯Jquery绘制这些。 I think currently Data Table does not allow dynamic column binding..:(
我认为目前数据表不允许动态列绑定.. :(
You can manage to do that by doing following steps; 您可以通过执行以下步骤来做到这一点;
According to your question, I have developed a json in following structure; 根据您的问题,我开发了以下结构的json;
{
regionName: "India",
outlets: [
{
outletName: "outlet1",
personName: "debrup",
count: "430"
}
]
}
Let me show you an example; 让我给你看一个例子。
$(document).ready(function() {
var jsonObj = [
{
regionName: "India",
outlets: [
{
outletName: "outlet1",
personName: "debrup",
count: "430"
},
{
outletName: "outlet12",
personName: "debrup2",
count: "440"
}
]
}
];
var html = '<table border="1">';
$.each(jsonObj, function(i, region) {
html += '<tr><td>' + region.regionName + '</th></tr>';
html += '<tr><td></td>'
$.each(region.outlets, function(x, outlet) {
html += '<td><b>' + outlet.outletName + '</b></td>';
});
html += '</tr><tr>';
html += '<td>personName</td>';
$.each(region.outlets, function(key, value) {
html += '<td>' + value.personName + '</td>';
});
html += '</tr><tr>';
html += '<td>count</td>';
$.each(region.outlets, function(key, val) {
html += '<td>' + val.count + '</td>';
});
html += '</tr>';
});
html += '</table>';
$("#table").html(html);
});
You can see working fiddle here: http://jsfiddle.net/Y8qHZ/19/ . 您可以在这里看到工作的小提琴: http : //jsfiddle.net/Y8qHZ/19/ 。 Change json values and see how it works
更改json值并查看其工作方式
You shouldn't need to parse the json data to create the table - the DataTable plugin will do that for you if you invoke it correctly. 您不需要解析json数据即可创建表-如果正确调用DataTable插件,它将为您完成此操作。
In your code that generates the json data structure for the table rows, you can additionally generate a data structure for the table headers, and then pass them both in as parameters to the datatable initialization using the aaData and aoColumns parameters. 在为表行生成json数据结构的代码中,您还可以为表头生成数据结构,然后使用aaData和aoColumns参数将它们作为参数传递给数据表初始化。
It should be easy to generate the header data as you'll be looping through the columns when generating the row data. 生成标题数据应该很容易,因为在生成行数据时将遍历各列。
Works well for me anyway... 反正对我来说很好...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.