我的.json
文件如下:
{"Team1":
{
"Player1": {"minutes":"11:35", "tsr":"25.0"},
"Player2":{"minutes":"24:44", "tsr":"53.8"},
"Player3":{"minutes":"14:22", "tsr":"35.7"}
},
"Team2":
{
"PlayerX":{"minutes":"27:06", "tsr":"12.5"},
"PlayerY":{"minutes":"04:54", "tsr":"27.8"},
"PlayerZ":{"minutes":"03:21", "tsr":"33.7"}
}
}
我想回复一个表,如下所示:
<table>
<tr><td colspan='3'>Team1</td></tr>
<tr>
<td>Player1</td>
<td>11:35</td>
<td>25.0</td>
</tr>
<tr>
<td>Player2</td>
<td>24:44</td>
<td>53.8</td>
</tr>
<tr>
<td>Player3</td>
<td>14:22</td>
<td>35.7</td>
</tr>
<tr><td colspan='3'>Team2</td></tr>
<tr>
<td>PlayerX</td>
<td>27:06</td>
<td>12.5</td>
</tr>
<tr>
<td>PlayerY</td>
<td>04:54</td>
<td>27.8</td>
</tr>
<tr>
<td>PlayerZ</td>
<td>03:21</td>
<td>33.7</td>
</tr>
</table>
每支球队的球员数量不固定:可以是3或其他数字。
我正在使用jquery刷新.json
文件。这是当前(和坏)的jquery代码。它应该是这样的:
var pdatafile = "json/pdata.json";
$.getJSON(pdatafile, function (pjson) {
for (i = 0; i < pjson.Team1.length; ++i) {
// Code
}
for (i = 0; i < pjson.Team2.length; ++i) {
// Code
}
});
有谁能告诉我如何使这个jquery代码工作以及如何在jquery中打印表?
答案 0 :(得分:1)
我做了一个小提琴,说我是不是你想要的:)。
https://fiddle.jshell.net/ydwf5hks/1/
let myJson = {
"Team1":
{
"Player1": {"minutes":"11:35", "tsr":"25.0"},
"Player2":{"minutes":"24:44", "tsr":"53.8"},
"Player3":{"minutes":"14:22", "tsr":"35.7"}
},
"Team2":
{
"PlayerX":{"minutes":"27:06", "tsr":"12.5"},
"PlayerY":{"minutes":"04:54", "tsr":"27.8"},
"PlayerZ":{"minutes":"03:21", "tsr":"33.7"}
}
}
let html = [];
for(let team in myJson){
let teamName = team;
html.push('<table>');
html.push('<tr><td colspan="3">' + teamName + '</td></tr>')
for(let player in myJson[team]){
let playerName = player;
html.push('<tr><td>' + playerName + '</td><td>' + myJson[team][player].minutes + '</td><td>' + myJson[team][player].tsr + '</td></tr>');
}
html.push('</table>');
}
document.getElementById('content').innerHTML = html.join('');
<div id="content">
</div>
答案 1 :(得分:0)
for (i = 0; i < Object.keys(pjson.Team1).length; ++i) {
do_something(pjson.Team1[Object.keys(pjson.Team1)]);
}
这样的事情应该有效
答案 2 :(得分:0)
var output="";
for(teamname in pjson){
var team=pjson[teamname];
output+=" <tr><td colspan='3'>"+teamname+"</td></tr>";
for(playername in team){
player=team[playername];
output+="<tr><td>"+playername+"</td><td>"+player.tsr+"</td><td>"+player.minutes+"</td></tr>";
}
}
document.body.innerHTML=output;
您可以使用两个循环进行迭代并构建html ...