【问题标题】:Creating an HTML table using JavaScript and JSON使用 JavaScript 和 JSON 创建 HTML 表格
【发布时间】:2017-05-11 19:59:11
【问题描述】:

我正在尝试使用来自 JSON 输入的 JavaScript 创建一个 HTML 表,但是它不适合我。

我在 HTML 中使用了标记。这将从 Javascript 中的 innerHTML 调用中填充:

for (var i = 0; i < json.data.length; i++) {
  listItem = json.data[i].number + "--" + "( Widget " + json.data[i].widget_id + ") x " + "  " + json.data[i].pence_price + " GBP" + json.data[i].number * json.data[i].pence_price + " GBP";
  table.push(listItem);
}
document.getElementById('updateOrder').innerHTML = table;

这给了我以下输出:

11--Widget 8 x 10GBP 110GBP, 10--Widget 9 x 10GBP 100GBP

我想要的是以下内容:

11--Widget 8 x 10GBP                  110GBP
10--Widget 9 x 10GBP                  100GBP

数字、小部件和成本左对齐,总数右对齐。我还希望在不同的行上单独订购。

JSON 中的数据是:

{"id":"9518","order_id":"11380","widget_id":"9","number":"10","pence_price":"12"}

我一直在用这个拉头发;任何帮助或指导将不胜感激。

【问题讨论】:

  • 我没有看到任何表格,我也没有看到类似 flex 的东西,我看到你正在将某些东西推入数组(其中缺少声明)。所以现在你有一组连接的字符串......那么你希望你的表如何构建,作为一个 html 表或一个带有 div 的?
  • 你说得对,我想把它放到一个表中,但我只想挑选某些 json 组件。如您所知,我对 JS 并不是特别熟练,如果我设法拼凑的东西可以变成一张桌子,我将不胜感激。 PS。这是通过cordova为Android手机编写的。
  • 一种没有行的表格格式,如果这只是通过使用 div - 那么是通过 div。
  • 感谢您编辑我的帖子,它看起来像我想要的那样。

标签: javascript html json


【解决方案1】:

var json = {data:{a: {"id":"9518","order_id":"11380","widget_id":"9","number":"10","pence_price":"12"},b:{"id":"9518","order_id":"11380","widget_id":"9","number":"10","pence_price":"12"},c: {"id":"9518","order_id":"11380","widget_id":"9","number":"10","pence_price":"12"}}}
var i,
    item,
    listItem = "";
for (i in json.data){
    item = json.data[i];
    listItem += "<div class='table'><div>"+item.number+"--"+"( Widget "+item.widget_id+") x "+"  "+item.pence_price+" GBP</div><div class='right'>"+item.number*item.pence_price+" GBP</div></div>";
}
document.getElementById('updateOrder').innerHTML=listItem;
#updateOrder{
  padding: 2px;
  background: orange;
}
.table{
  width: 100%;
  background: green;
  display: table;
}
.table > div{
  display: table-cell;
}
.right{
  background: tomato;
}
&lt;div id="updateOrder"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    我创建了一个有点大的模板,它为您提供了一种可能的方式来创建表格、为其添加一些样式并进行一些潜在的计算。

    我尽我所能添加尽可能多的 cmets 来描述代码在做什么。

    既然你提到你想要一个 html 表格,它是用基本的table 元素创建的,并添加了一些基本样式来区分页眉、行和页脚

    // the data used in this demo
    var data = [{
        "id": "9518",
        "order_id": "11380",
        "widget_id": "9",
        "number": "10",
        "pence_price": "12"
      },
      {
        "id": "9518",
        "order_id": "11380",
        "widget_id": "9",
        "number": "10",
        "pence_price": "12"
      }
    ];
    
    function createTable(target, data, columns) {
      // gets the elements required based on id for the target div
      // and creates the table, thead, tbody & tfoot for the table
      let element = document.getElementById(target),
        table = document.createElement('table'),
        thead = document.createElement('thead'),
        header = document.createElement('tr'),
        tbody = document.createElement('tbody'),
        tfoot = document.createElement('tfoot');
    
      // creates the header
      columns.forEach(column => {
        // and creates the cells in the header, adding title and class
        let cell = document.createElement('td');
        cell.innerHTML = column.title;
        cell.className = column.class;
        header.appendChild(cell);
      });
      thead.appendChild(header);
    
      // totals is used for the totals for the footer
      var totals = {};
      for (let i = 0; i < data.length; i++) {
        // creates the single rows
        let row = document.createElement('tr');
        columns.forEach(column => {
          // and for each column creates the cell itself
          let cell = document.createElement('td');
          let value;
          // checks what to display
          if (column.field) {
            // only a property on the data
            value = data[i][column.field];
          } else if (column.value) {
            // a function with a callback value
            value = column.value(data[i])
          }
          // if it should calculate totals, it will do so here
          if (column.calculateTotal) {
            // in case the column is unknown, it's initialized as 0
            // warning: all values will be whole numbers
            totals[column.field] = (totals[column.field] || 0) + parseInt( value );
          }
          // if it has a template, we will replace the %0 with value
          // this template function supports only 1 value to be "templated"
          if (column.template) {
            value = column.template.split('%0').join(value);
          }
          // set the cell value
          cell.innerHTML = value;
          // set the class (used to align, for example)
          cell.className = column.class;
          // add cell to row
          row.appendChild(cell);
        });
        // add row to tbody
        tbody.appendChild(row);
      }
      // empty object would mean false, so only if totals needed to be calculated
      // would it create the footer here
      if (totals) {
        let row = document.createElement('tr');
        columns.forEach( column => {
          let cell = document.createElement('td'), value = '';
          if (column.calculateTotal) {
            value = totals[column.field];
            if (column.template) {
              // can still use the row template
              value = column.template.split('%0').join(value);
            }
          }
          cell.innerHTML = value;
          cell.className = column.class;
          row.appendChild( cell );
        });
        tfoot.appendChild( row );
      }
      table.appendChild(thead);
      table.appendChild(tbody);
      table.appendChild(tfoot);
      // set the table on the target element
      // warning, calling create table twice will create 2 tables under eachother
      element.appendChild(table);
    }
    
    // call the create table, with the:
    // - target: id in html -> 'target'
    // - data: an array defining your data itself 
    // - columns: an array of objects describing how the table should look
    //    - title: header
    //    - field (optional): which property it should show
    //    - value (optional): callback function that receives a row and should return a value
    //    - calculatedValue (optional): bool indicating if columns should be summed
    //    - template (optional): any text you wish to add to your data?
    createTable('target', data, [{
        title: 'id',
        field: 'id',
        class: 'left'
      },
      {
        title: 'order',
        field: 'order_id',
        class: 'left'
      },
      {
        title: 'widget',
        field: 'widget_id',
        class: 'left'
      },
      {
        title: 'number',
        field: 'number',
        class: 'center'
      },
      {
        title: 'price',
        field: 'pence_price',
        class: 'right',
        template: '%0 GBP'
      },
      {
        title: 'total',
        value: (row) => parseInt(row['number']) * parseInt(row['pence_price']),
        class: 'right',
        template: '%0 GBP',
        calculateTotal: true
      }
    ]);
    .left {
      text-align: left;
    }
    .right {
      text-align: right;
    }
    thead tr {
      background-color: #777;
    }
    thead tr td {
      font-weight: bold;
      color: #fff;
    }
    tfoot tr td {
      font-weight: bold;
    }
    table td {
      padding: 5px;
      border-bottom: solid #efefef 1px;
    }
    <div id="target">
    </div>

    【讨论】:

    • 感谢 Icepickle 抽出宝贵时间,这也有效,但是上面 avril 的答案对我来说更容易实现。
    • @KevinSullivan Cool :) 只要你找到了答案,一切都很好:) 我还根据你的第一篇文章创建了示例代码,没有进行编辑以及它的外观和如您所描述的 html 表。虽然是真的 avril 的代码更容易使用
    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2018-05-27
    • 2012-12-06
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多