日期:2014-05-16  浏览次数:20324 次

如何在脚本里面表动态添加一行?
hi,
比如我有这样的一个表在我的aspx   (2.0   with   ajax   support)
<table   id= "table1 ">
<tr   id= "tr1 ">
<td> this   is   the   first   line </td>
</tr>
<tr   id= "tr2 ">
<td> this   is   the   second   line </td>
</tr>

我需要在tr2前面插入一行。我感觉虽然我这里没有放TBODY,但用alert(document.getElementById( "table1 ").innerHTML)   发现好像是他自动加了一个tbody.   我试图使用insertBefore(newtr,   tr2Obj),   但发现他只能用在table1上,不能用在tbody   上.



------解决方案--------------------
<script>
function addRow()
{
var obj=document.getElementById( 'table1 ');
var insertRow = obj.insertRow(1);
var td=insertRow.insertCell();
td.innerHTML= 'add 1 row ';
}
</script>

<table id= "table1 ">
<tr id= "tr1 ">
<td> this is the first line </td>
</tr>
<tr id= "tr2 ">
<td> this is the second line </td>
</tr>
<a onclick= "add() "> 插入一行 </a>
------解决方案--------------------

<script>
//tbody 是默认存在的。
function addRow()
{
var table = document.getElementById( 'table1 ');

var row = document.createElement( 'tr ');
var cell = document.createElement( 'td ');
cell.innerHTML = 'abcd ';

row.appendChild(cell)

table.childNodes(0).appendChild(row);
}
</script>
<div>
<table id= "table1 ">
<tr>
<td> 1234 </td>
</tr>
</table>
</div>
<input onclick= "addRow(); " type= "button " value= "Add Row ">
------解决方案--------------------
insertRow()可以带参数,参数表示要增加的行的位置
先获得tr2的行号,然后tb.insertRow(tr2_rowIndex);就可以加在tr2的行前
------解决方案--------------------
<script>
var tab = document.getElementById( "表名 ");
var row = tab.insertRow(); //新规一个行对象
var cell1 = row.insertCell(0);// 新规一个列对象
</script>
然后通过 cell1.insertHTML来添加具体内容,也可通过cell1.name等等设置属性