Optional. Integer that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
你方法用错了,插入行应该用insertRow,看我的<table width="800" border="1" cellspacing="0" cellpadding="5" id="t1">
<tr>
<td>1 </td>
<td>2 </td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr id="bf">
<td id="cf">5</td>
<td>6</td>
</tr>
</table>
<script>
function fun(){
var tb=document.getElementById("t1")
var row=tb.insertRow(2)
row.insertCell().innerHTML=7
row.insertCell().innerHTML=8
}
fun()
</script>
因为ie的兼容性问题(table节点下没法添加tr节点),原表格必须在table节点下有tbody节点,所有的tr节点都是在tbody节点之下。当我们要添加行的时候,创建tr节点,然后添加到tbody节点之下,再创建对应的td节点,添加到tr节点之下就行了。
测试代码如下:
<table>
<tbody id="myTableBody">
<tr>
<td>第一行</td>
</tr>
<tr>
<td>第二行</td>
</tr>
</tbody>
</table>
<input type="button" value="追加行" onclick="appendRow()" />
<script type="text/javascript">
function appendRow() {
var tableBody = document.getElementById('myTableBody')
var newRow = document.createElement('tr')
tableBody.appendChild(newRow)
var td = document.createElement('td')
td.innerHTML = '新行'
newRow.appendChild(td)
}
另外楼下提到的insertRow也可以 不过要注意加上参数-1, 这样才可以兼容Firefox。但是insertCell就显得不怎么好用了,因为用insertCell生成的td是没法用innerHTML赋值的
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)