javascript创建table

本文介绍了一个使用JavaScript和DOM接口创建并填充HTML表格的方法。通过简单的脚本,可以在页面加载时动态生成包含特定文本内容的表格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<html>
<head>
<title>Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces</title>
<script>
   function start() {
       // get the reference for the body
       var mybody = document.getElementsByTagName("body")[0];

       // creates a <table> element and a <tbody> element
       mytable     = document.createElement("table");
       mytablebody = document.createElement("tbody");

       // creating all cells
       for(var j = 0; j < 2; j++) {
           // creates a <tr> element
           mycurrent_row = document.createElement("tr");
           for(var i = 0; i < 2; i++) {
               // creates a <td> element
               mycurrent_cell = document.createElement("td");
               // creates a text node
               currenttext = document.createTextNode("cell is row "+j+", column "+i);
               // appends the text node we created into the cell <td>
               mycurrent_cell.appendChild(currenttext);
               // appends the cell <td> into the row <tr>
               mycurrent_row.appendChild(mycurrent_cell);
           }
           // appends the row <tr> into <tbody>
           mytablebody.appendChild(mycurrent_row);
       }
       // appends <tbody> into <table>
       mytable.appendChild(mytablebody);
       // appends <table> into <body>
       mybody.appendChild(mytable);
       // sets the border attribute of mytable to 2;
       mytable.setAttribute("border", "2");
   }
</script>
</head>
<body οnlοad="start()">
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值