Creating an HTML table using JavaScript and JSON

前端 未结 2 1139
北荒
北荒 2021-01-29 06:16

I am trying to create an HTML table using JavaScript from a JSON input, however, it\'s not working out for me.

I am using a marker in the HTML. This will get populated f

相关标签:
2条回答
  • 2021-01-29 06:27

    I created a bit larges template which gives you a possible way to create a table, add some styling to it, and do some potential calculations.

    I did my best to add as much comments as possible describing what the code is doing.

    Since you mentioned you wanted an html table, it is created with the basic table element, and some basic styles were added to differentiate between header, rows and footer

    // 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>

    0 讨论(0)
  • 2021-01-29 06:35

    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;
    }
    <div id="updateOrder"></div>

    0 讨论(0)
提交回复
热议问题