简体   繁体   English

将tr附加到表会使用JavaScript将新的tbody附加到html表

[英]Appending tr to table appends a new tbody to html table using javascript

Please check this fiddle: http://jsfiddle.net/tn4euhsn/8/ 请检查此小提琴: http : //jsfiddle.net/tn4euhsn/8/

HTML: HTML:

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

Javascript: 使用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);

I am trying to append a new <tr> to a table. 我试图将新的<tr>追加到表中。 But instead a <tbody><tr></tr></tbody> gets appended, resulting in 2 <tbody> elements in html table. 但是取而代之的是附加了<tbody><tr></tr></tbody> ,在html表中产生了2个<tbody>元素。

So whats wrong here? 那这怎么了? and how do I do it? 以及我该怎么做? (I don't want to use jquery) (我不想使用jQuery)

Yes it already has a default tbody tag so you have to use it instead of introducing new one. 是的,它已经具有默认的 tbody标签,因此您必须使用它而不是引入新的标签。

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

Also you can simplify it like 你也可以简化它

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

Update: 更新:

While trying to figure out the reason, I came across HTMLTableElement , 在尝试找出原因时,我遇到了HTMLTableElement

If a table has multiple tbody elements, by default, the new row is inserted into the last tbody . 如果一个表具有多个tbody元素,则默认情况下,新行将插入到最后一个tbody To insert the row into a specific tbody 将该行插入特定的tbody

Here is an updated version of the above code 这是上述代码的更新版本

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 小提琴

It seems that the browser will give it a tbody by default, try this: 看来浏览器默认会给它一个提示,试试这个:

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

Append to the tbody not to the table. 附加到肢体而不是桌子上。

Updated Fiddle 更新的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM