我有2个表,当我尝试将第二个子表追加到表1(tbl1)时,table2(tbl2)自动删除<table...>标记:

function myFunction() {
    var tabletr = document.getElementById("tbl1");
    var rowtr = tabletr.insertRow(1);
    rowtr.appendChild(document.getElementById("tbl2"));

    rowtr.outerHTML = "<div>" + rowtr.outerHTML + "</div>";

}

<table id='tbl1' style='background: lightblue;'>
<tr>
<td>table 1 - 1-1</td>
<td>table 1 - 1-2</td>
</tr>
<tr>
<td>table 1 - 2-1</td>
<td>table 1 - 2-2</td>
</tr>
</table>
<br />
<hr />
<table id='tbl2' style='background: lightgray;'>
<tr>
<td>table 2 - 1-1</td>
<td>table 2 - 1-2</td>
</tr>
</table>


<button onclick="myFunction()">Try it</button>

屏幕截图:
javascript - 无法在Tr&gt; Div中追加Child-LMLPHP

最佳答案

需要将div放入单元格中。



function myFunction() {
    var tabletr = document.getElementById("tbl1");
    var rowtr = tabletr.insertRow(-1);
    var cell = rowtr.insertCell(0);
    cell.colSpan = 2;
    var div = document.createElement("div");
    div.appendChild(document.getElementById("tbl2"));
    cell.appendChild(div);
}

<table id='tbl1' style='background: lightblue;'>
  <tr>
  <td>table 1 - 1-1</td>
  <td>table 1 - 1-2</td>
  </tr>
  <tr>
  <td>table 1 - 2-1</td>
  <td>table 1 - 2-2</td>
  </tr>
</table>
<br />
<hr />
<table id='tbl2' style='background: lightgray;'>
  <tr>
  <td>table 2 - 1-1</td>
  <td>table 2 - 1-2</td>
  </tr>
</table>


<button onclick="myFunction()">Try it</button>

关于javascript - 无法在Tr> Div中追加Child,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47124889/

10-12 13:01