JavaScript案例(三):动态渲染页面;html+css+js实现动态渲染页面


前言

将代码中已知的数据结构,通过代码的方式把数据渲染成一个表格显示在页面上


如图: 

 

循环遍历users数组,有多少个成员执行多少回

1. 创建一个tr标签

2. 循环遍历 users内的每一个对象

对象内有多少个成员,执行多少遍

2-1.创建一个td标签

2-2. 向 td标签内添加内容

2-3. 把td标签插入到tr标签内

3. 把tr 插入到tbody内部

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>案例:动态渲染页面</title>
    <style>
        table{
            width: 300px;
            text-align: center;
        }
    </style>
</head>
<body>
    <table border="1" cellspacing="0">
        <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>年龄</th>
            </tr>
        </thead>
        <tbody>
        <!--        js渲染-->
        </tbody>
    </table>

    <script>
        //提前准备好的数据
        var users = [
            {id: 1, name: '张三', age: 18},
            {id: 2, name: '李四', age: 28},
            {id: 3, name: '王麻子', age: 38}
        ]

        //获取tbody标签
        var tbody = document.querySelector('tbody')

        //1.循环遍历users数据
        users.forEach(function (item) {
            //这里的item 就是数组中的每一个对象
            console.log(item)
            //2. 每一个对象生成一个tr标签
            var tr = document.createElement('tr')

            //循环遍历item
            for(var key in item){
                //生成td标签
                var td = document.createElement('td')
                td.innerHTML = item[key]

                //5.把td 插入到tr内部
                tr.appendChild(td)
            }
            //把本次的tr插入到tbody的内部
            tbody.appendChild(tr)
        })
    </script>
</body>
</html>

文章参考视频:b站千锋前端学习营:千锋前端JavaScript全套教程_JS零基础完美入门到项目实战https://www.bilibili.com/video/BV1W54y1J7Ed?share_source=copy_web 

全部评论

相关推荐

Z_eus:别打招呼直接发你的优势
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务