简体   繁体   English

如何使用JSON数据在四列中创建HTML表?

[英]How to create HTML table in four columns using JSON 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 我有一个要用JSON数据呈现的HTML表,根据我的要求,我必须在4列中显示Data,无论数据的大小是多少

Issue 问题

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 当我的data.length被4均等时,它将显示两行四列,但是当它的长度为6时它将显示两行3-3列,这是不正确的,如果我的数据长度为5然后它只显示4个项目,而不是第5个项目,我不知道我在犯什么错误

My code 我的密码

 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> 

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 在我的JSON中,我共有Items但它仅显示4,我在代码中注释了我认为问题所在的行

I would make it simple and do it this way: 我将使其简化并以这种方式进行:

 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(data, columns = 4, container = "#DisplayTable") { var tableHtml = ''; tableHtml += '<table class="table table-striped table-bordered">'; tableHtml += ' <tbody>'; var totalRows = Math.ceil(data.length / columns); for (let i = 0; i < totalRows; i++) { tableHtml += ' <tr>'; for (let j = 0; j < columns; j++) { let dataIndex = i * columns + j; if (typeof data[dataIndex] != 'undefined') { tableHtml += ' <td class="text-left color' + (j + 1) + '">' + data[dataIndex]["Item Name"] + '</td>'; tableHtml += ' <td class="text-left color' + (j + 1) + '">' + data[dataIndex]["Quantity"] + '</td>'; } else { tableHtml += ' <td class="text-left color' + (j + 1) + '"></td>'; tableHtml += ' <td class="text-left color' + (j + 1) + '"></td>'; }; }; tableHtml += ' </tr>'; }; tableHtml += ' <tbody>'; tableHtml += '</table>'; $(container).html(tableHtml); }; 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> <div id="DisplayTable"></div> 

Also on JSFiddle . 同样在JSFiddle上

Your first loop runs 1 times less than you want it to, and I'm not sure how your second loop works. 您的第一个循环运行的次数比您希望的要少1倍,我不确定您的第二个循环的工作方式。 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);

        });
      }

Each object within the array has 4 entries so to fill 4 columns each object will fill a row with the columns 1 and 3 having the keys and 2 and 4 for the values. 数组中的每个对象都有4个条目,因此要填充4列,每个对象将用具有键的键1和3以及值的键2和4填充一行。 Details are commented in demo. 演示中将评论详细信息。

 const data = [{ "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 }]; /** genTable(selector, [...array]) @Param: selector [String]: element to append table to [...array][Array]: copy of the array of objeccts */ //A - Append htmlString of table to the given element /*B - for...of loop of the given array by static method .entries() [index, object] destructed assignment allows easy access */ /*C - $('table')[0] is a jQ Object dereferenced to a jS Object in order to use the JS method .insertRow() */ //D - Same as B but with Object.entries() on each object of array /*E - On each key/value pair of current object .insertCell() and assign the text of each cell with the key then the value */ function genTable(selector, [...array]) { $(selector).append(`<table class='table table-striped table-bordered table-hover'><tbody></tbody></table>`); //A for (let [index, object] of array.entries()) { //B let row = $('table')[0].insertRow(); //C for (let [key, value] of Object.entries(object)) { //D row.insertCell().textContent = key; //E row.insertCell().textContent = value; //E } } } genTable('main', [...data]) 
 tr td:first-of-type { background: #4AD184; } tr td:nth-of-type(2) { background: #EA69EF; } tr td:nth-of-type(3) { background: #E1A558; } tr td:last-of-type { background: #F4F065; } 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <main></main> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script> 

 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 }, { "Item Name": "JAMESON 750", "Quantity": 49 }, { "Item Name": "JIM BEAM WHITE 750", "Quantity": 409 }] function addTable(tableValue) { var container = $( "#DisplayTable" ); $.each(tableValue, function(key, value) { var item = $('<div />', { 'class': 'item' }).appendTo(container); var Name = $('<div />', { 'text': value["Item Name"]}).appendTo(item); var Quantity = $('<div />', { 'text': value["Quantity"],'class':'count'}).appendTo(item); }); } $( document ).ready(function() { addTable(tableValue); }); 
 #DisplayTable{ display:grid; grid-template-columns: auto auto auto auto; } .item{ border:1px solid white; display:flex; align-items:center; padding:10px; border-radius:3px; background:yellow; color:#fff; } .count{ font-weight:500; font-size:3em; } .item:nth-child(4n-7) { background-color:green; } .item:nth-child(4n-6) { background-color:red; } .item:nth-child(4n-5) { background-color:blue; } .item:nth-child(4n-4) { background-color:black; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script> <div id="DisplayTable"></div> 

Use Grid and flex instead of table. 使用网格和伸缩而不是表。 If you want to avoid Grid then use column-count. 如果要避免使用Grid,请使用column-count。 See the snippet. 请参阅摘要。

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

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