简体   繁体   English

使用JSON中的嵌套jQuery生成表

[英]Generating a table using nested jQuery from JSON

I'm trying to generate a table from some JSON data. 我正在尝试从一些JSON数据生成一个表。

What i'm trying to get is basically a list of publishers, each of that publisher's Authors, and each of that authors book details. 我想要得到的基本上是出版商列表,该出版商的每个作者以及每个作者的书籍详细信息。 So using the JSON below it would look something like: 因此,使用下面的JSON看起来像:

Publisher      |  Author     |  BookDetails
-------------------------------------
Random House   |  John Smith |  Provided, 3, fiction
Penguin        |  William S  |  Not Provided, 5, fiction

A publisher will have more than one author and an author may have more than one book Details, in which case it would look like: 出版商将有不止一位作者,而一位作者可能有不止一本书详细信息,在这种情况下,它看起来像:

Publisher      |  Author        |  BookDetails
-------------------------------------
Random House   | John Smith     | Provided, 3, fiction
               |                | Another, John Smith Book
Penguin        | William S      | Not Provided, 5, fiction
               | Another Author | Another Authors details
               |                | Second book by another author

My JSON looks like: 我的JSON看起来像:

 JSONCollection = {
                       "genres": [{
                           "genre": "Horror",
                               "publishers": [{
                               "publisherName": "Random House",
                                   "authors": [{
                                   "authorName": "John Smith",
                                       "bookDetails": [{
                                       "Blurb": "Provided",
                                           "Review": 3,
                                           "Type": "Fiction"
                                   }]
                               }]
                           }]
                       }, {
                           "genre": "Romance",
                               "publishers": [{
                               "publisherName": "Penguin",
                                   "authors": [{
                                   "authorName": "William Shakespeare",
                                       "bookDetails": [{
                                       "Blurb": "Not Provided",
                                           "Review": 5,
                                           "Type": "Fiction"
                                   }]
                               }]
                           }]
                       }]
                   }

The code i'm using (just to get the Publisher/author to work so far) is: 我正在使用的代码(只是为了使发布者/作者能够正常工作)是:

  var table = $('#dataTable')
           var table_thead = table.find('thead')
           table_thead.empty()
           var tr_head = $('<tr>')
               .append($('<th>').text('publishers'))
               .appendTo(table_thead)
           var table_tbody = table.find('tbody')
           table_tbody.empty()
           var tr_body = $('<tr>')
           for (var i = 0; i < JSONCollection.genres.length; i++) {
               for (j = 0; j < JSONCollection.genres[i].publishers.length; j++) {
                   tr_body.append($('<td />').text(this.publisherName))
                       .appendTo(table_tbody)
                   for (k = 0; k < JSONCollection.genres[i].publishers[j].authors.length; k++) {
                       tr_body.append($('<td />').text(this.authorName))
                           .appendTo(table_tbody)
                   }
               }
           }

But it doesn't seem to be working, the Publisher header is generated and then nothing after that, i'm not receiving any errors in the console. 但这似乎不起作用,生成了Publisher标头,然后此后什么也没有,我在控制台中没有收到任何错误。 Any ideas where i'm going wrong? 任何想法,我要去哪里错了?

Here's a fiddle: http://jsfiddle.net/hE52x/ 这是一个小提琴: http : //jsfiddle.net/hE52x/

Thanks 谢谢

I think what you need is this Fiddle 我想你需要的是这个小提琴

var table = $('#dataTable');
var table_thead = $('#dataTable thead');
var table_tbody = $('#dataTable tbody');
var buffer="";
table_thead.html('<th>publishers</th><th>Authors</th>');

for (var i = 0; i < JSONCollection.genres.length; i++) {
    buffer+='<tr>';
    for (j = 0; j < JSONCollection.genres[i].publishers.length; j++) {
        buffer+='<td>'+JSONCollection.genres[i].publishers[j].publisherName+'</td>';
        buffer+='<td>';
        for (k = 0; k < JSONCollection.genres[i].publishers[j].authors.length; k++) {
            buffer+=(k==0?'':', ')+JSONCollection.genres[i].publishers[j].authors[k].authorName;
        }
        buffer+='</td>';
    }
    buffer+='</tr>';

}
table_tbody.html(buffer);

I have modified the Fiddle here Fiddle 我在这里修改了小提琴

in the fiddle replaced 在小提琴中替换

this.publisherName with JSONCollection.genres[i].publishers[j].publisherName this.publisherNameJSONCollection.genres[i].publishers[j].publisherName

Instead i used $.each() to do this: 相反,我使用$.each()来做到这一点:

$.each(JSONCollection.genres, function (i, item) {
    $.each(item.publishers, function (i, item) {
        tr_body.append($('<td />').text(item.publisherName)).appendTo(table_tbody);
        $.each(item.authors, function (i, item) {
            tr_body.append($('<td />').text(item.authorName)).appendTo(table_tbody);                           
        });
    });
});

Demo 演示版


As a side note: 附带说明:

A table only can have <thead>, <tbody> as a direct child. 一个表只能将<thead>, <tbody>作为直接子级。 The correct markup should be follow like this: 正确的标记应如下所示:

<h2>Books</h2> <!--This should not be a direct child of table-->

<table id="dataTable">
  <thead></thead>
  <tbody></tbody>
</table>

here i have tuned your code a bit 在这里,我对您的代码进行了一些调整

Jquery Code: jQuery代码:

                JSONCollection = {
                   "genres": [{
                       "genre": "Horror",
                           "publishers": [{
                           "publisherName": "Random House",
                               "authors": [{
                               "authorName": "John Smith",
                                   "bookDetails": [{
                                   "Blurb": "Provided",
                                       "Review": 3,
                                       "Type": "Fiction"
                               }]
                           }]
                       }]
                   }, {
                       "genre": "Romance",
                           "publishers": [{
                           "publisherName": "Penguin",
                               "authors": [{
                               "authorName": "William Shakespeare",
                                   "bookDetails": [{
                                   "Blurb": "Not Provided",
                                       "Review": 5,
                                       "Type": "Fiction"
                               }]
                           }]
                       }]
                   }]
               }

               var table = $('#dataTable')
                var table_thead = table.find('thead')
                table_thead.empty()
                var tr_head = $('<tr>')
                   .append($('<th>').text('Publishers'))
                   .append($('<th>').text('Author'))
                   .appendTo(table_thead)
                var table_tbody = table.find('tbody')
                table_tbody.empty()
                var tr_body = $('<tr>')
                for (var i = 0; i < JSONCollection.genres.length; i++) {
                   var tr_body = $('<tr>');
                   for (j = 0; j < JSONCollection.genres[i].publishers.length; j++) {
                       $this = JSONCollection.genres[i].publishers[j];
                       alert(JSONCollection.genres[i].publishers[j].publisherName);
                       tr_body.append($('<td />').text($this.publisherName))
                           .appendTo(table_tbody)
                       for (k = 0; k < JSONCollection.genres[i].publishers[j].authors.length; k++) {
                           $this = JSONCollection.genres[i].publishers[j].authors[k];
                           tr_body.append($('<td />').text($this.authorName))
                               .appendTo(table_tbody)
                       }
                   }
               }

LIVE DEMO: 现场演示:

http://jsfiddle.net/dreamweiver/hE52x/19/ http://jsfiddle.net/dreamweiver/hE52x/19/

Happy Coding :) 快乐编码:)

Four loops are needed to achieve this. 为此,需要四个循环。 I used $.each() to achieve this. 我用$.each()实现了这一点。

The first loops through the genres, the second through the publishers, the third though the authors and the last through book details. 第一个循环浏览各种类型,第二个循环通过发行者,第三个循环通过作者,最后一个循环通过书籍详细信息。 It will take care of publishers having more than one author and one author having more than one book/title. 它将照顾出版者有多于一位作者和出版者多于一本书/书名的出版商。

The initial HTML for the table is as follows: 该表的初始HTML如下:

<table border="1" cellpadding="5" cellspacing="0" id="dataTable">
    <thead>
        <tr>
            <td>Publisher</td>
            <td>Author</td>
            <td>Book Details</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>

The jQuery code is very as follows: jQuery代码非常如下:

var tbody = $('#dataTable').find('tbody'),
    tr = $('<tr/>'),
    td = $('<td/>'),
    genres = JSONCollection.genres,
    row;
$.each(genres, function(index, genre) {
    $.each(genre.publishers, function(i,publisher) {
        $.each( publisher.authors, function(j, author) {
            row = tr.clone().html( td.clone().html( publisher.publisherName ) )
            .append( td.clone().html( author.authorName ) ).append( td.clone() );
            $.each(author.bookDetails, function(l,book) {
                row.find( 'td' ).eq( 2 ).append( (l>0)?'<br>':'' )
                .append( book.Blurb + ', ' + book.Review + ', ' + book.Type );
            });
            row.appendTo( tbody );
        });
    });
});

JS FIDDLE DEMO JS FIDDLE DEMO

EDIT 编辑

The demo has been adjusted to show how the code would handle multiple authors and books. 该演示已进行了调整,以显示该代码将如何处理多个作者和书籍。 The code was slightly adjusted. 代码略有调整。 A CSS rule was added too. 一个CSS规则也增加了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM