Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

javascript - Create HTML table using jQuery and JSON array

I'm having difficulty trying to create an HTML table from a returned JSON string. Here's the JSON:

{
    "Heading 1": ["name 1", "name 2", "name 3"],
    "Heading 2": ["data 1", "data 2", "data 3"],
}

The Table should look like this:

<table>
    <thead>
        <tr>
            <th>Heading 1</th>
            <th>Heading 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>name 1</td>
            <td>data 1</td>
        </tr>
        <tr>
            <td>name 2</td>
            <td>data 2</td>
        </tr>
        <tr>
            <td>name 3</td>
            <td>data 3</td>
        </tr>
    </tbody>
</table>

I gave the "head" created, but can't figure out the "body".

var table = $('<table/>'),
    table_head = $('<thead/>'),
    head_row = $('<tr/>');

$.each(val, function (th, items) {
    head_row.append('<th>' + th + '</th>');

    var body_row = $('<tr/>');
    $.each(items, function (index, item) {

        // What do to here to create <td>'s ?!?!

    });
    console.log(items);
});

table_head.append(head_row);
table.append(table_head);

Just can't get the logic to work. There are more headings in the returned JSON and tried to simplify for illustration. Please help, and thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's better to just concatenate strings than create jQuery objects.

var json = {
    "Heading 1": ["name 1", "name 2", "name 3"],
    "Heading 2": ["data 1", "data 2", "data 3"],
};

var headings = Object.keys(json);

var html = '<table>';

// build table headings
html += '<thead><tr>';
$.each(headings, function () {
  // this is the current heading
  html += '<th>' + this + '</th>';
});
html += '</tr></thead>';


// build table body
html += '<tbody>';
// use the length of first array to determine how many rows
for (i = 0, len = json[headings[0]].length; i < len; i++) {
  html += '<tr>';
  // build each cell using the heading's ith element
  $.each(headings, function () {
    html += '<td>' + json[this][i] + '</td>';
  });
  html += '</tr>';
}
html += '</tbody>';
html += '</table>';

$('.container').append(html);
table {
  border-collapse: collapse;
}
th, td {  
  border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...