天天看点

Nearth===>WEB前端--第24课/JQuery/动态创建元素5(动态创建表格案列)

代码学习:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        body{
                     background-image: url(0.jpg);
                     background-repeat: no-repeat;
                     background-attachment: fixed;
                     background-size: 100% 100%;
        }
        table {
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #c0c0c0;
        }

        th,
        td {
            border: 1px solid #d0d0d0;
            color: #404060;
            padding: 10px;
        }

        th {
            background-color: #09c;
            font: bold 16px "微软雅黑";
            color: #fff;
        }

        td {
            font: 14px "微软雅黑";
        }

        tbody tr {
            background-color: #f0f0f0;
        }

        tbody tr:hover {
            cursor: pointer;
            background-color: #fafafa;
        }
    </style>
    <script src="jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
    <script>
        // 模拟从后台拿到的数据
        var datas = [
            {
                name: "传智播客",
                url: "http://www.itcast.cn",
                type: "IT最强培训机构"
            },
            {
                name: "黑马程序员",
                url: "http://www.itheima.com",
                type: "大学生IT培训机构"
            },
            {
                name: "传智前端学院",
                url: "http://web.itcast.cn",
                type: "前端的黄埔军校"
            }];

        //页面加载后,点击按钮,遍历数组,获取数组中的元素内容,创建行和列,加入到表格中的tbody中
      /* $(function (){
          $("#btnCreate").click(function () {
               //遍历数组
             for(var i=0;i<datas.length;i++){
                   var obj=datas[i];//数组中的每一个对象
                   //创建行和列,加入到tbody中
                   $("<tr> <td><a href="+obj.url+">"+obj.name+"</a></td>      <td>"+obj.type+"</td> </tr>").appendTo($("#tbd"));
               }
            });
        }); */
        $(function () {
            $("#btnCreate").click(function () {
                var arr=[];
                //遍历数组
                for(var i=0;i<datas.length;i++){
                    var obj=datas[i];//数组中的每一个对象
                    //创建行和列,加入到tbody中
                    arr.push("<tr><td><a href="+obj.url+">"+obj.name+"</a></td>      <td>"+obj.type+"</td></tr>");
                }
                $("#tbd").html(arr);
            });
        });
    </script>
</head>

<body>
<input type="button" value="获取数据" id="btnCreate"style="width: 150px;height: 50px;"/>
<hr >
<div>
    <table>
        <thead>
        <tr>
            <th>名称</th>
            <th>说明</th>
        </tr>
        </thead>
        <tbody id="tbd">
        </tbody>
    </table>
</div>
</body>
</html>      

运行结果:

让自己的每一天都过得有质量·······································