原生table动态渲染树形结构数据


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <table border style="width: 500px;" cellspacing='0'>
    <thead>
      <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
        <th>4</th>
      </tr>
    </thead>
    <tbody id="tbody"></tbody>
  </table>
  <script>
    const tbody = document.getElementById('tbody');
    let data = [{
      name: "1",
      children: [{
          name: "1-1",
          children: [{
            name: "1-1-1",
            children: [{
              name: "1-1-1-1"
            }]
          }, {
            name: "1-1-2",
            children: [{
                name: "1-1-2-1"
              },
              {
                name: "1-1-2-2"
              }
            ]
          }, {
            name: "1-1-3",
            children: [{
                name: "1-1-3-1"
              },
              {
                name: "1-1-3-2"
              }, {
                name: "1-1-3-3"
              }
            ]
          }]
        },
        {
          name: "1-2",
          children: [{
            name: "1-2-1",
            children: [{
              name: "1-2-1-1"
            }]
          }]
        }
      ]
    }];

    function setRowspan(arr = [], p = null) {
      arr.forEach((item, index) => {
        if (item.children && item.children.length > 0) {
          setRowspan(item.children, item);
          item.rowspan = item.children.reduce((pre, next) => {
            pre += next.rowspan || 1;
            return pre;
          }, 0);
        }
        item.idx = index;
        item.p = p;
      });
    }

    setRowspan(data);


    function createTable(arr = []) {
      arr.forEach((item, index) => {
        if ((item.children && item.children.length > 0)) {
          createTable(item.children);
          if (item.p && index === 0) {
            item.str = item.children.reduce((pre, next) => {
              return (pre += next.str);
            }, `<td rowspan="${item.rowspan}">${item.name || ""}</td>`);
          } else {
            item.str = item.children.reduce((pre, next) => {
              return (pre += next.str);
            }, `<tr><td rowspan="${item.rowspan}">${item.name || ""}</td>`);
          }
        } else {
          item.str = "";
          if (index !== 0) {
            item.str = `<tr>`;
          }
          item.str += `
            <td>${item.name}</td>
            </tr>
          `;
        }
      });
    }
    createTable(data)
    let str = '';
    data.forEach(item => {
      str += item.str
    })
    tbody.innerHTML = str
  </script>
</body>

</html>

 

 
效果:
 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM