【问题标题】:Populating a table with an object with JQuery使用 JQuery 用对象填充表
【发布时间】:2014-10-11 06:31:13
【问题描述】:

我有一个对象数组对象[{Date, Count, City}]

假设我有这些数据

[{01/01/01, 10, New York}, {01/01/01, 15, London}, {01/01/01, 16, Rome},{02/01/01, 40, New York},{02/01/01, 25, London}, {02/01/01, 36, Rome}]

我想使用 JQuery 填充一个 html 表并得到以下结果

Date     | New York | London | Rome
01/01/01 | 10       | 15     | 16
02/01/01 | 40       | 25     | 36

是否可以用JQuery生成类似这样的表?

这是我到目前为止所做的代码

for (var i = 0; i < countResult.length; i++) {
        var html = "<table><thead><tr><th>Date</th><th>City</th><th>Count</th></thead><tbody>";
        for (var j = 0; j < countResult[i].length; j++) {
            html += "<tr>";
            html += "<td>" + countResult[i][j].date + "</td><td>" + countResult[i][j].city + "</td><td>" + countResult[i][j].count+ "</td>";
        }
        html += "</tr>";

        html += "</tbody></table></br>";
        $(html).appendTo("#div");
    }

【问题讨论】:

  • 你一定尝试过什么?如果显示一下
  • 是的,有可能。
  • 是的,我已经尝试过了,但我正在用整个对象填充表格。我将用我到目前为止所做的代码更新问题

标签: javascript jquery html json html-table


【解决方案1】:

我的问题的解决方案是:

    var countResult = [    
      ["01/01/01", 10, "New York"],    
      ["01/01/01", 15, "London"],     
      ["01/01/01", 16, "Rome"],     
      ["02/01/01", 40, "New York"],     
      ["02/01/01", 25, "London"],    
      ["02/01/01", 36, "Rome"]     
    ]  
    var cities = []

   $.each(countResult, function(rowNum, row) {
       var city = row[2];      
       if($.inArray(city, cities) < 0) cities.push(city);      
   });

    var html = "<table><thead><tr><th>Date</th>"
       + $.map(cities, function (c) {      
           return "<th>" + c      
    }).join("") + "</tr></thead><tbody>";          

    var summary = {};

    $.each(countResult, function
      (rowNum, row) {      
        if(!summary[row[0]]) summary[row[0]] = {}    
        summary[row[0]][row[2]] = row[1];      
    });

    $.each(summary, function (date, counts) {     
        html += "<tr><td>" + date;
        $.each(counts, function (i, ct) {     
           html += "<td>" + ct     ; 
        });      
        html += "</tr>";      
    });      
    $(html).appendTo("#div");

【讨论】:

    【解决方案2】:

    试试这个代码

                var html='<table>';
                var arObj = YOUR ARRAY OBJECT;
                    $(arObj).each(function(i, u) {
    
                        var Date = u[0];
                        var count = u[1];
                        var City=u[2];
                       html=html+'<tr><td>'+Date+'</td><td>'+count+'</td><td>'+City+'</td><td>';
    
                    });
                html=html+'</table>';
    

    现在追加到 html

    $('#myDiv').append(html);
    

    【讨论】:

    • 感谢您的回答,但此代码给出的结果与我上面发布的代码给出的结果相同。我想要一张与我在问题中发布的表格相似的表格
    猜你喜欢
    • 2016-01-12
    • 2016-06-27
    • 2012-11-28
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多