我想使用从 API 检索到的 JSON 数据创建一个表,但 jQuery 总是将元素放在错误的位置......
这是我的 jQuery 代码:
var container = $("#container");
var table = $("#table");
$(document).ready(function() {
callAPI();
});
function callAPI() {
$.ajax({
url: "action-api.php",
method: "GET",
dataType: 'json',
success: function(data) {
console.log(data);
container.append('<table style="width:100%"><tr><th>ID</th><th>Naam</th> <th>Brouwerij</th><th>Type</th><th>Gisting</th><th>Percentage</th><th>Inkoop Prijs</th></tr>');
$.each(data, function(i, item) {
container.append('<tr><td>' + item.id + '</td>');
container.append('<td>' + item.naam + '</td>');
container.append('<td>' + item.brouwerij + '</td>');
container.append('<td>' + item.type + '</td>');
container.append('<td>' + item.gisting + '</td>');
container.append('<td>' + item.perc + '</td>');
container.append('<td>' + item.inkoop_prijs + '</td></tr>');
});
container.append('</table>');
},
});
}
这是 HTML 输出:
最佳答案
您必须创建table
和与td
分隔的行tr
,否则它们将在追加后自动关闭,例如当你这样做时:
container.append('<tr><td>' + item.id + '</td>');
输出将是:
<tr><td>item.id</td></tr>
____________________^^^^^ //NOTE the closed tag will be added automatically
所以你只需将它们分开:
var table = $('<table style="width:100%"></table>');
table.append('<tr><th>ID</th><th>Naam</th> <th>Brouwerij</th><th>Type</th><th>Gisting</th><th>Percentage</th><th>Inkoop Prijs</th></tr>');
$.each(data, function(i, item) {
var tr = $('<tr/>');
tr.append('<td>' + item.id + '</td>');
tr.append('<td>' + item.naam + '</td>');
tr.append('<td>' + item.brouwerij + '</td>');
tr.append('<td>' + item.type + '</td>');
tr.append('<td>' + item.gisting + '</td>');
tr.append('<td>' + item.perc + '</td>');
tr.append('<td>' + item.inkoop_prijs + '</td>');
table.append(tr);
});
container.append(table);
希望这有帮助。
关于javascript - jQuery 将 JSON 数据附加到表中总是将元素放在错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41956211/