javascript - 如何使用 jQuery JSON 创建表?

标签 javascript jquery json html-table jsonp

谁能帮我弄清楚每次循环开始时如何添加 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/

相关文章:

javascript - 从数组中删除一个对象

javascript - AngularJS/javascript - 将唯一值对象展平为简单列表

python - 如何在 AWS Glue pyspark 脚本中合并两个节点

javascript - 如何处理 Knockout ViewModel 中的空对象和满对象

javascript - 如何使用 jQuery 在 HTML 字符串中查找元素并更改属性

javascript - D3 物理重力

jquery - Android 设备上的子菜单中的链接不起作用

javascript - 我收到未捕获的 TypeError : Cannot read property 'length' of null on jquery. main.js

javascript - Rails - 使用 AJAX 时刷新页面而不是部分页面

javascript - 在 jQuery slider 移动时获取其值