谁能帮我弄清楚每次循环开始时如何添加 tr 行。下面是我的 jQuery 代码:
var row = $("<tr></tr>");
$.each(data.response.docs, function (i, item) { // json is the name of the object
row.append('<td>' + item.adServerId + '</td>'); //item is named at the opening of this $.each function
row.append('<td>' + item.advertiserId + '</td>');
row.append('<td>' + item.advertiserName + '</td>');
row.append('<td>' + item.campaignId + '</td>');
row.append('<td>' + item.campaignName + '</td>');
row.append('<td>' + item.bookedImps + '</td>');
row.append('<td>' + item.imps + '</td>');
row.append('<td>' + item.clicks + '</td>');
row.append('<td>' + item.ctr + '</td>');
row.append('<td>' + item.postViewConvs + '</td>');
row.append('<td>' + item.postViewConvsRate + '</td>');
row.append('<td>' + item.convs + '</td>');
row.append('<td>' + item.convsRate + '</td>');
row.append('<td>' + item.targetRevenue + '</td>');
row.append('<td>' + item.revenue + '</td>');
row.append('<td>' + item.cost + '</td>');
row.append('<td>' + item.startDate + '</td>');
row.append('<td>' + item.endDate + '</td>,</tr>');
$("#adcampaignGrid").append(row);
最佳答案
$.each(data.response.docs, function (i, item) {
var row = $("<tr></tr>");
for (var i in item) row.append($('<td>').text(item[i]));
$("#adcampaignGrid").append(row);
});
或者如果所有键都不需要:
$.each(data.response.docs, function (i, item) {
var props = [
'adServerId',
'advertiserId',
'advertiserName',
'campaignId',
'campaignName',
'bookedImps',
'imps',
'clicks',
'ctr',
'postViewConvs',
'postViewConvsRate',
'convs',
'convsRate',
'targetRevenue',
'revenue',
'cost',
'startDate',
'endDate'
];
var row = $("<tr></tr>");
for (var i in props) row.append($('<td>').text(item[props[i]]));
$("#adcampaignGrid").append(row);
});
关于javascript - 如何使用 jQuery JSON 创建表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12084160/