JavaScript生成一个简单的表格

需要代码简单生成一表格即可。在网上搜了不少,运行后没有效果。TKS 。

<input type="button" value="创建一个新表格" onclick="createTable(800,8,5)" />
<script type="text/javascript">
//方法参数createTable(表格宽度[不要单位],行数,列数)
function createTable(width,rows,cells)
{
//创建一个表格对象
var mytable=document.createElement("table");
mytable.cellSpacing="1px";
//创建一个表头对象
var mythead=document.createElement("thead");
for(a=0;a<1;a++)
{
var myrow=document.createElement("tr");
for(b=0;b<cells;b++)
{
var mytd=document.createElement("td");
mytd.innerHTML="表 头 " +(b+1);
mytd.style.cssText="text-align:center;";
myrow.appendChild(mytd);
}
mythead.appendChild(myrow);
}
//创建一个表体对象
var mytbody=document.createElement("tbody");
for(i=0;i<rows;i++)
{
var myrow=document.createElement("tr");
for(j=0;j<cells;j++)
{
var mytd=document.createElement("td");
mytd.style.backgroundColor="#fff";
mytd.innerHTML="第"+(i+1)+"行第"+(j+1)+"列";
myrow.appendChild(mytd);
}
mytbody.appendChild(myrow);
}
//创建一个表脚对象
var mytfoot=document.createElement("tfoot");
for(c=0;c<1;c++)
{
var myrow=document.createElement("tr");
for(d=0;d<1;d++)
{
var mytd=document.createElement("td");
mytd.innerHTML="脚"+(d+1);
mytd.style.cssText="text-align:center;";
mytd.colSpan="10";
myrow.appendChild(mytd);
}
mytfoot.appendChild(myrow);
}
//将表头追加到表格
mytable.appendChild(mythead)
//将表体追加到表格
mytable.appendChild(mytbody);
//将表脚追加到表格
mytable.appendChild(mytfoot);
//追加对象样式
mythead.style.cssText="background-color:#003; color:#FFF; font-size:14px; font-weight:600; width:"+width+"px;";
mytable.style.cssText="background-color:#999; border:0px; width:"+width+"px;";
mytfoot.style.cssText="background-color:#003; color:#FFF; font-size:14px; font-weight:600; width:"+width+"px;";
document.body.appendChild(mytable);
}

//调用示例[创建一个宽度为800px,有100行,5列的表格]
createTable(800,100,5);
</script>
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-20
document.write("标签");直接打印标签
第2个回答  2011-12-08
gjghkhjlk;