用js怎么建表格?

JavaScript024

用js怎么建表格?,第1张

<input type="button" value="创建一个新表格" onclick="createTable(800,8,5)" />

<script type="text/javascript">

function createTable(width,rows,cells)

{

//创建一个表格对象

var mytable=document.createElement("table")

mytable.cellSpacing="1px"

//创建一个表头对象

var mythead=document.createElement("thead")

for(a=0a<1a++)

{

var myrow=document.createElement("tr")

for(b=0b<cellsb++)

{

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=0i<rowsi++)

{

var myrow=document.createElement("tr")

for(j=0j<cellsj++)

{

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=0c<1c++)

{

var myrow=document.createElement("tr")

for(d=0d<1d++)

{

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:#003color:#FFFfont-size:14pxfont-weight:600width:"+width+"px"

mytable.style.cssText="background-color:#999border:0pxwidth:"+width+"px"

mytfoot.style.cssText="background-color:#003color:#FFFfont-size:14pxfont-weight:600width:"+width+"px"

document.body.appendChild(mytable)

}

</script>

<HTML>

<script language="javascript">

var tableObj = null

function newTable(){

tableObj = document.createElement( "table" )

tableObj.border = "1"

divObj.appendChild( tableObj )

newRow.style.display = "block"

}

function AddRow(){

if( tableObj == null )

newTable()

var trObj = tableObj.insertRow() // 加一行

for(var i = 0i <3i ++){

var tdObj = trObj.insertCell() // 加一列

tdObj.innerText = tableObj.rows.length + "_" + (i + 1)

}

}

</script>

<BODY>

<button onclick="newTable()">创建表格</button><button id="newRow" style="display: none" onclick="AddRow()">添加新行</button>

<div id="divObj"></div>

</BODY>

</HTML>