使用jQuery和JSON数组创建HTML表 [英] Create HTML table using jQuery and JSON array

查看:135
本文介绍了使用jQuery和JSON数组创建HTML表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难尝试根据返回的JSON字符串创建HTML表.这是JSON:

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"],
}

表格应如下所示:

<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);

只是无法使逻辑起作用.返回的JSON中包含更多标题,并尝试简化以进行说明.请帮忙,并预先感谢!

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!

推荐答案

根据需要创建tr元素,然后使用index推送td元素

create tr element if needed then use index to push td element

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

var table = $('<table/>'),
  table_head = $('<thead/>'),
  head_row = $('<tr/>'),
  table_body = $('<tbody/>'),
  body_row = [];

$.each(json, function(th, items) {
  head_row.append('<th>' + th + '</th>');
  $.each(items, function(index, item) {
  
    if (body_row[index] === undefined) {
      body_row[index] = $('<tr/>');
      body_row[index].append('<td>' + item + '</td>');
    } 
    else
      body_row[index].append('<td>' + item + '</td>');
  });
  
  //console.log(items);
});

table_head.append(head_row);
table_body.append(body_row)
table.append(table_head);
table.append(table_body);
$('body').html(table)

table {
  border-collapse: collapse;
}
th, td {  
  border: 1px solid #ccc;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于使用jQuery和JSON数组创建HTML表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆