JS的渲染表格案例

302 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    table {
      text-align: center;
      border: 1px solid pink;
    }
  </style>
</head>
<body>
  <table cellpadding='0' cellspacing="1">
    <thead>
      <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>班级</th>
      </tr>
    </thead>
    <tbody>
      <!-- <tr>
        <td>1</td>
        <td>张三</td>
        <td>17</td>
        <td>男</td>
        <td>2XX</td>
      </tr> -->
    </tbody>
  </table>
  <script>
    /**
     * 需求:
     *    1.接收后端给到的数据
     *    2.将数据渲染到页面
     * */ 
    // 1.写一个数组,模拟接收到了后端的数据
    var users = [
      {
        id: 1,
        name: '张三',
        age: 17,
        gender: '男',
        classRoom: '2XX'
      },
      {
        id: 2,
        name: '李四',
        age: 66,
        gender: '女',
        classRoom: '2XX'
      },
      {
        id: 3,
        name: '王五',
        age: 18,
        gender: '男',
        classRoom: '2XX'
      }
    ]
    /**
     * 2.将数据渲染到页面
     * 
     *    思路:1.将数组内的数据,转换为我们盂要的字符串
     *          2.通过innerHTML插入到页面渲染出来 
     * 
     *  ``包裹的内容和''包裹起来的一样,都是一个字符中,但是``可以换行,而''不能换行
     *    两者的区别:
     *          1.``可以换行,''不能换行
     *          2.``内部书写${} 这个{}里面可以书写变量
     * */ 

    //  0.获取元素
    var tBodyEle = document.querySelector('tbody')
    // 1.将数组内的数据,转换为我们需要的字符串
    var str = ''
    users.forEach(function(item) {
      // console.log(item)
      // str += '<tr><td>1</td><td>张三</td><td>17</td><td>男</td><td>2XX</td></tr>'
      str += `<tr>
        <td> ${ item.id } </td>
        <td> ${ item.name } </td>
        <td> ${ item.age } </td>
        <td> ${ item.gender } </td>
        <td> ${ item.classRoom } </td>
      </tr>`
    })
    // console.log(str)

    // 2.通过innerHTML插入到页面渲染出来 
    tBodyEle.innerHTML = str
  </script>
</body>
</html>