首页 > 解决方案 > 在表格底部动态添加一行

问题描述

使用 JavaScript,在 AngularJS 应用程序的上下文中,我试图在表的末尾添加一行,以显示特定列的总和。

在以下代码中:

  var table = document.querySelector('.table');
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cellData = document.createTextNode('Total ' + '$' + this.totals);
  cell1.appendChild(cellData);
  row.appendChild(cell1);

使用 insertRow(-1) 不起作用。我能够看到我的行的唯一方法是如果我传入零作为第一个参数。与 insertRow(0) 中一样,但该行作为一行插入到表头中。

这是我的完整代码:

import { digest, showLoader } from 'act/services/events';
import 'act/components';
import Searcher from 'act/services/lists/searcher';
import * as moment from 'moment';
import * as api from '../services/totals';
import {header, dev} from 'act/services/logger';
import {goToError} from 'act/services/controller-helpers';
import '../components/store-total';
const defaultStartDate = moment().startOf('day');

export default class StoreTotalsController {
  constructor() {
    this.attendantNames = [];
    this.stores = [];
    this.emptyResult = true;
    this.totals = 0;
  }

  getAttendants() {
    showLoader('Searching');
    const baseUrl = '/src/areas/store-totals/services/tender-total-data.json';
    const getStores = new Request(baseUrl, {
      method: 'GET'
      });
    fetch(getStores).then(function(response){
      return response.json();
    }).then(resp => {
    if (!(resp[0] && resp[0].error)) {
      this.attendantNames = resp.stores[0].attendants;
      this.attendantNames.forEach(a=>{
        this.totals += a.total;
        console.log(this.totals);
      })

      var table = document.querySelector('.table');
      var row = table.insertRow(0);
      var cell1 = row.insertCell(0);
      var cellData = document.createTextNode('Total ' + '$' + this.totals);
      cell1.appendChild(cellData);
      row.appendChild(cell1);

      this.emptyResult = false;
      this.errorMessage = null;

    } else {
      this.errorMessage = resp[0].error.name;
    }
    digest();
    showLoader(false);
    });
  }

  searchIfReady() {
    if (this.search && this.date && this.date.isValid()) {
      this.getSearch();
    }
  }

  updateDate(date) {
    this.date = moment(date).startOf('day');
    this.searchIfReady();
  }
}
StoreTotalsController.$inject = ['$stateParams'];

标签: javascriptangularjs

解决方案


有几种方法可以解决这个问题,使用 ngFor 绑定到新更新的数组,等等。模板,装订,各种新颖奇特的方式。最终的建议可能是“不要使用桌子”。

但是如果你必须使用一个表格,而你真正想做的只是追加另一个 HTML 行,那么这个老把戏就行得通(尽管它可能会引起 Angular 合唱的嚎叫)。请注意,您正在操作 innerHTML。您还可以使用文档片段对其进行更新,使其更加面向 OOP。

为什么是身体?使用 querySelector 和 console.log 选择表。您会看到行被包裹在一个 tbody 中。

这是超天真的版本。虽然有效。回到 AngularJS 时代,有时这种事情会让你准时回家。

<html>
<head>
<body>
    <table>
    <tr>
    <td>Row 1</td>
    </tr>
    </table>

    <button onclick="addRow ()">Click Me</button>

    <script>
        function addRow ( ) {
        const tbody = document.querySelector ( 'tbody' );
        let inner = tbody.innerHTML;
        inner += '<tr><td>Row 2 (compute value as necessary)</td></tr>';
        tbody.innerHTML = inner;
    }
    </script>
</body>
</html>

推荐阅读