JS插入節點實現創建表格

<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>自動創建表格</title>  
    <style type="text/css">  
        table{  
            width:300px;  
            height:100px;  
            border:#000 1px solid;  
            border-collapse:collapse;  
            }  
    </style>   
</head>  
<body>  
    <input type="text" id="line">行數<br>  
    <input type="text" id="list">列數<br>  
    <input type="button" value="添加表格" onclick="autocreate()">  
    <div id="d1" style="height:400px; width:300px;"></div>  
</body>
<script type="text/javascript" language="javascript">  
function autocreate(){  
    //創建table表格  
    var table=document.createElement("table");  
    table.setAttribute("border","10");  
    // table.setAttribute("background","red");  
    //獲取行數值  
    var line=document.getElementById("line").value;  
    //獲取列數值  
    var list=document.getElementById("list").value;

    for(var i=0;i<line;i++){  
        //alert(line);  
        //創建tr  
        var tr=document.createElement("tr");  
        for(var j=0;j<list;j++){  
            //alert(list);  
            //創建td  
            var td=document.createElement("td");  
            tr.appendChild(td);  
            }  
            table.appendChild(tr);  
        }  
        document.getElementById("d1").appendChild(table);  
    }  
</script>   
</html>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容