此脚本生成4个jquery ui选项卡,其中包含4个html表,
如何组合这些表格以在单个表格中进行组合,附上最终表格的屏幕截图。
var data = $.parseJSON("{\"version\":\"5.2\",\"user_type\":\"online\",\"user\":[{\"name\":\"John\",\"id\":50},{\"name\":\"John\",\"id\":51},{\"name\":\"John\",\"id\":57},{\"name\":\"John\",\"id\":98}]}");
const setTables = new Set();
$.each(data.user, function(key, value) {
let table;
var row = $("<tr/>");
if ($('table#main_table_' + value.id).length)
table = $("#main_table_" + value.id);
else
table = $('<table class="table table-responsive table-hover table-bordered"></table>');
table.attr('id', 'main_table_' + value.id);
row.append($("<td/>").text(value.name));
row.append($("<td/>").text(value.id));
table.append(row);
if(!setTables.has(value.id)) {
table.append( $("<thead><tr><th>NAME</th><th>ID</th></tr></thead>") );
setTables.add(value.id);
$( "#ul-tabs" ).append("<li><a href=\"#tabs-"+ value.id +"\">"+value.name+"</a></li>");
$( "#tabs" ).append("<div id=\"tabs-"+value.id+"\">"+table.prop('outerHTML')+"</div>");
}
});
$( "#tabs" ).tabs();
答案 0 :(得分:1)
我重构你的代码来实现这个目标。
var data = $.parseJSON("{\"version\":\"5.2\",\"user_type\":\"online\",\"user\":[{\"name\":\"John\",\"id\":50},{\"name\":\"John\",\"id\":51},{\"name\":\"John\",\"id\":57},{\"name\":\"John\",\"id\":98},{\"name\":\"XYZ\",\"id\":1},{\"name\":\"XYZ\",\"id\":50},{\"name\":\"XYZ\",\"id\":45},{\"name\":\"XYZ\",\"id\":98}]}");
let names = data.user.map(i => i.name)
.filter((el, i, a) => a.indexOf(el) == i);
function idsForName(name, array) {
return array.filter(el => el.name === name).map(el => el.id);
}
let $table = $('<table class="table table-responsive table-hover table-bordered"></table>');
$table.attr('id', 'main_table');
let $thead = $("<thead/>");
let $tbody = $("<tbody/>");
let $hRow = $("<tr/>").addClass('head-row');
if(names.length) $hRow.append($("<th/>").text('NAME'));
names.forEach(el => {
let $row = $("<tr/>");
$row.append($("<td/>").text(el));
let ids = idsForName(el, data.user);
ids.forEach((id, index) => {
let th = '.th-' + index;
if(!$hRow.find(th).length) $hRow.append($("<th/>").addClass('th-' + index).text('ID'));
$row.append($("<td/>").text(id));
});
$tbody.append($row);
});
$thead.append($hRow);
$table.append($thead).append($tbody);
$('#tabs').append($table.prop('outerHTML'))
&#13;
body{
margin: 20px;
}
th {
text-align: center;
}
td {
text-align: center;
}
table {
border-collapse: separate;
}
.table-responsive {
width: 100%;
}
div#export_excel {
float: right;
padding-right: 20px;
padding-top: 4px;
}
button#btnExport {
text-transform: uppercase;
font-weight: 100;
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tabs">
</div>
&#13;