天天看點

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>      

運作結果:

讓自己的每一天都過得有品質·······································