Javascript 为table添加行数据。

Javascript 为table添加行数据。,第1张

那是默认值,也可以不写,不写的话默认的也是-1,表示插入在当前集合的最后.HTML手册中的原文是:

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赋值的


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/7961590.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-12
下一篇 2023-04-12

发表评论

登录后才能评论

评论列表(0条)

保存