Posted on 2007-12-12 21:57
探佚 阅读(571)
评论(0) 编辑 收藏 所属分类:
CSS/JavaScript/AJAX
一、使用核心DOM创建表格(5行5列)
function createTableUseCore_DOM(rowCount,colCount)
{
// 创建<table/>元素
var oTable = document.createElement("table");
oTable.setAttribute("width","300px");
oTable.setAttribute("height","150px");
// 创建<tbody/>元素
var oTBody = document.createElement("tbody");
oTable.appendChild(oTBody);
// 创建5行5列
for(var i = 1 ; i <= rowCount ; i++)
{
var oTr = document.createElement("tr");
oTBody.appendChild(oTr);
for(var j = 1 ; j <= colCount ; j++)
{
var oTd = document.createElement("td");
var oText = document.createTextNode("<" + i + "," + j + ">");
oTd.appendChild(oText);
oTr.appendChild(oTd);
}
}
// 将<table>元素添加到<body>中输出
document.body.appendChild(oTable);
}
预览效果:

二、使用HTML DOM创建表格
// 使用HTML DOM建立表格
function createTableUseHTML_DOM(rowCount,colCount)
{
// 创建<table>元素
oTable = document.createElement("table");
oTable.setAttribute("id","table1");
oTable.setAttribute("width","300px");
// 创建<tbody/>元素
var oTBody = document.createElement("tbody");
oTable.appendChild(oTBody);
// 创建5行5列
for(var i = 0 ; i < rowCount ; i++)
{
// 创建一行
var oTr = oTBody.insertRow(i);
for(var j = 0 ; j <= colCount ; j++)
{
// 创建一个单元格
var oTd = oTr.insertCell(j);
var oText = document.createTextNode("<" + i + "," + j + ">");
oTd.appendChild(oText);
}
}
// 将<table>元素添加到<body>中输出
document.body.appendChild(oTable);
}
预览效果:
