我正在尝试将JSON数据加载到所需输出shuld看起来像
的HTML表中但我正在尝试
这是我的尝试
var data = {
"action":
[
{ "id": "1001", "type": "Matrix" },
{ "id": "1002", "type": "IP Man" },
{ "id": "1003", "type": "Revenge" }
],
"comedy":
[
{ "id": "2001", "type": "Iceman" },
{ "id": "2002", "type": "Pat & Mat" },
{ "id": "2003", "type": "Sugar" }
],
"animation":
[
{ "id": "3001", "type": "Frozen" },
{ "id": "3002", "type": "Tangled" },
{ "id": "3003", "type": "Croods" }
]
};
for (var i in data) {
$('#result').append('<table class="table table-striped"><thead><tr><th>Id</th><th>Type</th></tr></thead><tbody class="map"></tbody></table>');
}
var tds = '<tr>';
for (var j = 0; j < data[i].length; j++) {
var obj = data[i][j];
tds += '<td>' + obj.id + '</td>';
tds += '<td>' + obj.type + '</td>';
}
$('.map').append(tds);
&#13;
body {
background: white;
}
table {
margin: 10px;
border: 2px solid #eee;
}
td {
margin: 10px;
border: 2px solid #eee;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
&#13;
请告诉我如何解决这个问题?
答案 0 :(得分:1)
第一个问题:您打开了tr
元素,但尚未关闭它。第二个问题:你只分析最后一个“类别”(动画)。
var data = {
"action": [
{ "id": "1001", "type": "Matrix" },
{ "id": "1002", "type": "IP Man" },
{ "id": "1003", "type": "Revenge" }
],
"comedy": [
{ "id": "2001", "type": "Iceman" },
{ "id": "2002", "type": "Pat & Mat" },
{ "id": "2003", "type": "Sugar" }
],
"animation": [
{ "id": "3001", "type": "Frozen" },
{ "id": "3002", "type": "Tangled" },
{ "id": "3003", "type": "Croods" }
]
};
var result = $('#result');
for (var category in data) {
result.append(
'<table class="table table-striped"><thead>' +
'<tr><th>Id</th><th>Type</th></tr>' +
'</thead><tbody id="map_' + category + '"></tbody></table>'
);
for (var i = 0; i < data[category].length; ++ i) {
var item = data[category][i];
$('#map_' + category).append(
'<tr><td>' + item.id + '</td><td>' + item.type + '</td></tr>'
);
}
}
答案 1 :(得分:0)
您没有关闭for循环中的行。 您还需要在循环中包含和元素,因为您要添加行而不是单元格。
答案 2 :(得分:0)
var data = {
"action":
[
{ "id": "1001", "type": "Matrix" },
{ "id": "1002", "type": "IP Man" },
{ "id": "1003", "type": "Revenge" }
],
"comedy":
[
{ "id": "2001", "type": "Iceman" },
{ "id": "2002", "type": "Pat & Mat" },
{ "id": "2003", "type": "Sugar" }
],
"animation":
[
{ "id": "3001", "type": "Frozen" },
{ "id": "3002", "type": "Tangled" },
{ "id": "3003", "type": "Croods" }
]
};
var keys = Object.keys(data);
keys.forEach((key) => {
$('#result').append('<table class="table table-striped"><thead><tr><th>Id</th><th>Type</th></tr></thead><tbody class="map" id="'+key+'" ></tbody></table>');
data[key].forEach((obj) =>{
$('#'+key).append("<tr><td>"+obj.id+"</td><td>"+obj.type+"</td></tr>");
})
})
&#13;
body {
background: white;
}
table {
margin: 10px;
border: 2px solid #eee;
}
td {
margin: 10px;
border: 2px solid #eee;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
&#13;