js原生動態建立表格

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #box{
            border-collapse: collapse;
        }
    </style>
</head>
<body>
    <div id="box">

    </div>
    <!-- <table>
        <thead>
            <tr>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <a href="jvascript:;"></a>
                </td>
            </tr>
        </tbody>
    </table>
     -->
    <script>
        var datas=[
            { name: 'zs', sex: "男", subject: '語文', score: 90 },
            { name: 'ls', sex: "男", subject: '數學', score: 80 },
            { name: 'ww', sex: "女", subject: '英語', score: 60 },
            { name: 'zl', sex: "女", subject: '英語', score: 100 },
            { name: 'xs', sex: "女", subject: '英語', score: 60 },
            { name: 'dc', sex: "女", subject: '英語', score: 70 }
        ]
        var headDatas = ['姓名', '性別', '科目', '成績', '操做'];
        var box=document.getElementById("box");
        var table=document.createElement("table");
         /* 將建立的table添加到box裏面去 */
        box.appendChild(table);
        table.width="400px";
        table.border="1px";
        /* 動態建立thead */
        var thead=document.createElement("thead");
        table.appendChild(thead);
        thead.style.height="20px";
        thead.style.backgroundColor="purple";
        /* 動態建立th */
        var tr=document.createElement("tr");
        thead.appendChild(tr);
        /* 循環遍歷tr */
        for(var i=0;i<headDatas.length;i++){
            var th=document.createElement("th");
            tr.appendChild(th);
            th.innerText=headDatas[i];
         }
         /* 建立tbody */
         var tbody=document.createElement("tbody");
         tbody.style.textAlign="center";
         table.appendChild(tbody);
         /* 循環遍歷datas內容 */
         for(var i=0;i<datas.length;i++){
             var data=datas[i];
            var tr=document.createElement("tr");
            tbody.appendChild(tr);
            /* 遍歷data */
            for(var key in data){
                var td=document.createElement("td");
                tr.appendChild(td);
                td.innerText=data[key];
            }
            /* 添加a標籤 刪除 */
            var a=document.createElement("a");
            var th=document.createElement("th");
            th.appendChild(a);
            tr.appendChild(th);
            a.innerText="刪除";
            a.href="javascript:;";
            a.onclick=function(e){
                var name=prompt("我這麼可愛,真的要刪除我嗎?輸入yes我就消失啦");
                if(name=="yes"){
                    tbody.removeChild(this.parentNode.parentNode);
                }
            }   

         }
       

       
        
    </script>
</body>
</html>
相關文章
相關標籤/搜索