将tr添加到表中使用javascript将新tbody附加到html表

时间:2014-08-08 13:23:55

标签: javascript html

请检查这个小提琴:http://jsfiddle.net/tn4euhsn/8/

HTML:

<table id="tab" border=1>
    <tr>
        <td>A col1</td>
        <td>A col2</td>
    </tr>
</table>

使用Javascript:

console.log("Here!");
var table = document.getElementById("tab");
var trnew = document.createElement("tr");
trnew.id = "row" + 2;
var td1 = document.createElement("td");
td1.innerHTML= "r2col1";
var td2 = document.createElement("td");
td2.innerHTML= "r2col2";
trnew.appendChild(td1);
trnew.appendChild(td2);
table.appendChild(trnew);
console.log(table.outerHTML);

我正在尝试将新的<tr>附加到表格中。而是一个<tbody><tr></tr></tbody> 得到附加,在html表中产生2 <tbody>个元素。

这里有什么不对吗?我该怎么办? (我不想使用jquery)

2 个答案:

答案 0 :(得分:1)

它已经有默认 tbody标记,因此您必须使用它而不是引入新标记。

var table = document.getElementById("tab").getElementsByTagName('tbody')[0];

您也可以像

一样简化它
var table = document.getElementById("tab").getElementsByTagName('tbody')[0];
var trnew = document.createElement("tr");
trnew.id = "row" + 2;
for (var i=1; i<=2; i++) {
    var td = document.createElement("td");
    td.innerHTML = "r2col" + i;
    trnew.appendChild(td);   
}
table.appendChild(trnew);


console.log(table.outerHTML);

更新

在试图找出原因的同时,我遇到了HTMLTableElement

  

如果一个表有多个tbody元素,默认情况下,新行是   插入到最后tbody。将行插入特定的tbody

以下是上述代码的更新版本

var table = document.getElementById("tab");
var index = table.getElementsByTagName("tr").length;
var newRow = table.insertRow(index);
newRow.id = "row" + 2;
for (var i = 0; i < 2; i++) {
    var newCell = newRow.insertCell(i);
    var newText = document.createTextNode("r2col" + i);
    newCell.appendChild(newText);
}

console.log(table);

Fiddle

答案 1 :(得分:0)

默认情况下,浏览器会给它一个tbody,试试这个:

<table border=1>
    <tbody id="tab">
        <tr>
            <td>A col1</td>
            <td>A col2</td>
        </tr>
    </tbody>
</table>

附加到tbody而不是表格。

Updated Fiddle

相关问题