<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>javascript 动态生成表格</title>
</head>
<body>
<form id="form1" name="form1">
<table id="oTable">
<tbody id="oTBody">
</tbody>
</table>
<SCRIPT LANGUAGE="JScript">
function test()
{
var inputs=document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if(inputs[i].type=="text")
{
alert(inputs[i].id+"="+inputs[i].value);
}
}
}
// 接收参数<可修改>;
var rowNumbers=3; // 行;
var colNumbers=4; // 列;
// 设置表格属性;
var oCaption = oTable.createCaption(); // 在表格中创建空的 caption 元素;
var oTHead = oTable.createTHead();// 在表格中创建空的 tHead 元素;
var oTFoot = oTable.createTFoot(); // 在表格中创建空的 tFoot 元素;
var oRow, oCell;
var heading = new Array();
/*-------------列数 start------<head>-------*/
for(var i=0;i<colNumbers+1;i++)
{
if(i==0)
{
heading[i]="";
}
else
{
heading[i]="S"+(i);
}
}
oRow = oTHead.insertRow(); // insertRow()方法:在表格中创建新行(tr),并将行添加到 rows 集合中;
for (k=0; k<colNumbers+1; k++)
{
oCell = oRow.insertCell(); // insertCell()方法:在表格行(tr)中创建新单元格,并将单元格添加到 cells 集合中;
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.style.color="#ffffff";
oCell.innerHTML =heading[k];
if(k==0)
{
oCell.bgColor = "#ffffff";
}
else
{
oCell.bgColor = "#666666";
}
}
/*-------------列数 end-------------*/
/*-------------行数 start----<tbody>---------*/
var stock = new Array;
for(var i=0;i<rowNumbers;i++)
{
for(var j=0;j<colNumbers;j++)
{
if(j==0)
{
stock[""+i+","+j+""]="R"+(i+1);
}
else
{
stock[""+i+","+j+""]=j;
}
}
}
for (i=0; i<rowNumbers; i++)
{
oRow = oTBody.insertRow();
for (j=0; j<colNumbers+1; j++)
{
oCell = oRow.insertCell();
// 背景色;
if(j==0)
{
oCell.bgColor = "#999999";
}
else
{
oCell.bgColor = "#ffffff";
}
if(j==0)
{
oCell.innerHTML = stock[i + "," + j];
}
else
{
oCell.innerHTML = "<input type='text' id='"+stock[i+","+0]+"_S"+j+"' name='"+stock[i+","+0]+"_S"+j+"' value='' />";
}
}
}
/*-------------行数 end-------------*/
/*----------------------foot start*/
oRow = oTFoot.insertRow();
oCell = oRow.insertCell();
oCell.innerText="Author:maomao";
oCell.colSpan = colNumbers+1;
oCell.style.fontSize = "12";
oCell.align="center";
oCell.bgColor = "ffffff";
oCaption.style.fontSize = "12";
oCaption.align = "bottom";
/*----------------------foot end*/
function $(id) {
return document.getElementById(id);
}
</SCRIPT>
<input type="button" value="测试" onclick="javascript:test();" />
</form>
</body>
</html>