我有多个json文件,我正在尝试将它们加载到多个div内的表中。
这是我的json格式:
json1:
[
{
"id": 12345,
"code": "final",
"error": "",
"data": [
{
"metric": 4940616.0,
"title": "display"
},
{
"metric": 5132162.0,
"title": "platform"
},
{
"metric": 4954576.0,
"title": "subscribers"
},
{
"metric": 4882217.0,
"title": "unique_visitors"
}
}
json2
[
{
"run_id": 098765,
"code_title": "random",
"error": "",
"data": [
{
"col1": "abc",
"avg": 1,
"mean": 0,
"median": 3
},
{
"col1": "abc",
"avg": 1,
"mean": 2,
"median": 6
},
{
"col1": "abc",
"avg": 1,
"mean": 1,
"median": 6
}
]
}
]
JavaScript / jQuery代码:
const fn2 = (th, td) => {
$.getJSON(api, function(elem) {
elem.forEach(d => {
heads = Object.keys(d.data[0]);
col = Object.values(d.data);
heads.forEach(headers => {
$(th).append(`<th>${headers}</th>`);
});
col.forEach(cols => {
$(td).append(`<tr><td>${cols}</td></tr>`);
});
});
});
}
const fn = () => {
$('#d').append(`
<table border=1>
<thead>
<tr id='add_th_${codes}'>
</tr>
</thead>
<tbody id='td_${codes}'>
</tbody>
</table>
`);
fn2(`#add_th_${codes}`, `#td_${codes}`);
}
我能够将标题加载到多个表中,但无法将数据添加到其中。有没有办法做到这一点?我究竟做错了什么?
这是我当前的json1表的样子:
如何填充表格?我究竟做错了什么?
cols
具有类似的格式{"metric": 4940616.0, "title": "display"}
,因此您需要对其进行迭代以组装<td>
元素:
const fn2 = (th, td) => {
heads = Object.keys(d.data[0]);
col = Object.values(d.data);
for (var header of heads) {
$(th).append(`<th>${header}</th>`);
}
for (var cols of col) {
$(td).append(`<tr>`);
for (var val of Object.values(cols)) {
$(td).append(`<td>${val}</td>`);
}
$(td).append(`</tr>`);
}
}
var d = {"id": 12345, "code": "final", "error": "", "data": [
{"metric": 4940616.0, "title": "display"},
{"metric": 5132162.0, "title": "platform"},
{"metric": 4954576.0, "title": "subscribers"},
{"metric": 4882217.0, "title": "unique_visitors"}
]};
var codes = 1;
$('#d').append(`<table border=1><thead>
<tr id='add_th_${codes}'></tr></thead>
<tbody id='td_${codes}'></tbody></table>`);
fn2(`#add_th_${codes}`, `#td_${codes}`);
td, th { background: #333; color: white; padding: 1px 4px; font-size :13px; font-family: segoe ui; border: none; } thead, table { border: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="d"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句