如何使用JSON数据在四列中创建HTML表? [英] How to create HTML table in four columns using JSON data?

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

问题描述

我有一个用JSON数据呈现的HTML表,根据我的要求,我必须在4列中显示Data大小的数据

I have an HTML table which I am rendering with JSON data, according to My requirement I have to show Data in 4 columns what ever the size of data is

问题

当我的data.length被4均分时,它显示两行四列,但是当它的长度为6时,它显示两行3-3列,这是不正确的,如果我的数据具有长度为5,那么它只显示了4个项目,而不是第5个,我不知道我在犯什么错误

when my data.length is equally divided by 4 then it is showing two rows of four columns, But when it length is 6 then it is showing two rows of 3-3 columns which is not correct, If i have data having length of 5 then it is showing only 4 Items not the fifth one, I don't know what blunder I am making

我的代码

var tableValue = [{
  "Item Name": "JACK DANIELS 30",
  "Quantity": 292
}, {
  "Item Name": "JACK DANIELS 750",
  "Quantity": 731
}, {
  "Item Name": "JAMESON 30",
  "Quantity": 202
}, {
  "Item Name": "JAMESON 750",
  "Quantity": 49
}, {
  "Item Name": "JIM BEAM WHITE 750",
  "Quantity": 409
}]

function addTable(tableValue) {
  var $tbl = $("<table />", {
      "class": "table table-striped table-bordered table-hover "
    }),

    $tb = $("<tbody/>"),
    $trh = $("<tr/>");


  var split = Math.round(tableValue.length / 4); // here i Think some issue
  console.log(split)
  for (i = 0; i < split; i++) {
    $tr = $("<tr/>", {
      "class": "filterData"
    });
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {

        $("<td/>", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($tr);

      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);


}
addTable(tableValue);

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div id="DisplayTable"></div>

在我的JSON中,我总共有Items,但它仅显示4,我已在代码中注释了我认为问题所在的行

Here In my JSON I have total Items but it is showing only 4, I have commented the line where I think issue is in my Code

推荐答案

您的第一个循环运行的次数比您希望的少1倍,而且我不确定您的第二个循环的工作方式.将其更改为:

Your first loop runs 1 times less than you want it to, and I'm not sure how your second loop works. Change it to :

    for (i = 0; i <= split; i++) { // changed this
      $tr = $("<tr/>", {
        "class": "filterData"
      });
      for (j = 0; j < 4; j++) { 
        $.each(tableValue[(i*4) + j], function(key, value) { // changed this
            console.log(j)
          $("<td/>", {
            "class": "text-left color" + (j + 1)
          }).html(value).appendTo($tr);

        });
      }

这篇关于如何使用JSON数据在四列中创建HTML表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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