【问题标题】:How to create HTML table in four columns using JSON data?如何使用 JSON 数据在四列中创建 HTML 表?
【发布时间】:2019-06-05 18:38:40
【问题描述】:

我有一个 HTML 表格,我用 JSON 数据渲染,根据我的要求,我必须在 4 列中显示数据,无论数据大小是多少

问题

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

我的代码

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 个,我已经评论了我认为代码中存在问题的那一行

【问题讨论】:

  • 首先我明白了,不要使用round,而是使用Math.ceil()... 其他... 更好地创建纯html 代码,而不是附加... 更多:以防万一items%4 不为零,比您需要添加更多单元格...祝您好运。
  • @skobaljic 你是说要改变我的方法,正确的新代码?
  • 好吧,我会用其他方法,但你可以随心所欲。
  • @skobaljic 我没有得到这个想法除此之外我还做了很多事情,所以无法更改代码:(
  • 可以给我们画一张你想要达到的目标吗?没有视觉表示很难分辨。

标签: javascript jquery html html-table


【解决方案1】:

您的第一个循环比您希望的少 1 倍,我不确定您的第二个循环是如何工作的。改成:

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

        });
      }

【讨论】:

    【解决方案2】:

    我会让它变得简单,然后这样做:

    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>

    同样在JSFiddle

    【讨论】:

    【解决方案3】:

    数组中的每个对象都有 4 个条目,因此要填充 4 列,每个对象将填充一行,其中 1 和 3 列具有键,2 和 4 列具有值。详情在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>

    【讨论】:

      【解决方案4】:

      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>

      使用 Grid 和 flex 代替表格。如果您想避免使用 Grid,请使用列数。请参阅 sn-p。

      【讨论】:

        猜你喜欢
        • 2017-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-07
        相关资源
        最近更新 更多