用JavaScript为table创建tfoot元素

我编写了一个示例代码来在javascript中添加table的tfoot元素。

创建一个tfoot元素

要创建一个 tfoot 元素,可以使用“table element.createTFoot”。

<table id="tbl">
    <tbody>
        <tr>
            <th>苹果</th>
            <th>10</th>
        </tr>
        <tr>
            <th>香蕉</th>
            <th>20</th>
        </tr>
        <tr>
            <th>橘子</th>
            <th>30</th>
        </tr>
    </tbody>
</table>

<script>

const tbl = document.getElementById('tbl');

// 添加tfoot元素
const theElm = tbl.createTFoot();

// 添加tr元素
const trElm = theElm.insertRow();

// 添加th元素
let thElm = document.createElement('th');

// 添加文本节点
thElm.appendChild(document.createTextNode('总计'));

// 将th元素添加到tr元素
trElm.appendChild(thElm);

// 添加th元素
thElm = document.createElement('th');

// 添加文本节点
thElm.appendChild(document.createTextNode('60'));

// 将th元素添加到tr元素
trElm.appendChild(thElm);

</script>

此外,javascript 部分可以通过省略 document.getElementById 来编写。

// const tbl = document.getElementById('tbl'); ← 可省略此代码

// 添加tfoot元素
const theElm = tbl.createTFoot();

用JavaScript为table创建tfoot元素  第1张

示例代码

下面是一个示例代码,单击执行按钮时将一个tfoot元素添加到“table”中。

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>用JavaScript为table创建tfoot元素</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.2/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
  <div class="container text-center w-25" style="margin-top:150px">

    <table id="tbl" class="table p-4">
      <tbody>
        <tr>
          <th>苹果</th>
          <th>10</th>
        </tr>
        <tr>
          <th>香蕉</th>
          <th>20</th>
        </tr>
        <tr>
          <th>橘子</th>
          <th>30</th>
        </tr>
      </tbody>
    </table>

    <button id="result" class="btn btn-success btn-rounded ">执行</button>

  </div>

  <script>

    result.addEventListener('click', () => {

      // 添加tfoot元素
      const theElm = tbl.createTFoot();

      // 添加tr元素
      const trElm = theElm.insertRow();

      // 添加th元素
      let thElm = document.createElement('th');

      // 添加文本节点
      thElm.appendChild(document.createTextNode('总计'));

      // 将th元素添加到tr元素
      trElm.appendChild(thElm);

      // 添加th元素
      thElm = document.createElement('th');

      // 添加文本节点
      thElm.appendChild(document.createTextNode('60'));

      // 将th元素添加到tr元素
      trElm.appendChild(thElm);

    });

  </script>

</body>

</html>

执行结果

用JavaScript为table创建tfoot元素  第2张

本文来源:词雅网

本文地址:https://www.ciyawang.com/javascript-table-tfoot.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐