使用JavaScript和JSON创建HTML表

时间:2017-05-11 19:59:11

标签: javascript html json

我正在尝试使用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"}

我一直把头发拉出来;任何帮助或指导将不胜感激。

2 个答案:

答案 0 :(得分:0)

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

我尽力添加尽可能多的注释来描述代码正在做什么。

由于你提到你想要一个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>

答案 1 :(得分:0)

&#13;
&#13;
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;
&#13;
#updateOrder{
  padding: 2px;
  background: orange;
}
.table{
  width: 100%;
  background: green;
  display: table;
}
.table > div{
  display: table-cell;
}
.right{
  background: tomato;
}
&#13;
<div id="updateOrder"></div>
&#13;
&#13;
&#13;