用js实现动态添加表格数据

JavaScript014

用js实现动态添加表格数据,第1张

1、在页面div中事先创建一个空白表格,可以根据需求而定。

2、表格创建好后,我们就可以写动态生成表格的关键代码了。我们写一个js方法供触发使用。

3、在<tb>标签中我们添加了<input>标签,主要是用来提供用户输入参数, 而全局变量num,主要是用来区分每一个添加的参数的id的唯一性而存在的。

4、获得表格中的数据。

5、拿到表格中的数据后,我们根据它值的形式把它转换成json格式的数据。

<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>