gpt4 book ai didi

javascript - 在行内插入表格

转载 作者:行者123 更新时间:2023-11-28 00:51:26 25 4
gpt4 key购买 nike

我写了一个包含两个表的脚本:tbl1是一个主表,tbl2是我想插入到 tbl1 中的第二个表第二行使用 Pure JavaScript。它工作完美,但我的 tbl2有一些html attribute ,插入
后看到代码时没看到注意:tbl1tbl2两者都是相同的列标题,并且有两列。

function inserttbl2() {
var table = document.getElementById("tbl1");
var row = table.insertRow(1);
var celltr = row.insertCell(0);
row.innerHTML = document.getElementById("tbl2").outerHTML;
}
.myclass{
background-color: green;
color: white;
}
<!DOCTYPE html>
<html>

<body>

<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>

<table id="tbl1">
<tr>
<td>table 1</td>
<td>table 1</td>
</tr>
<tr>
<td>table 1</td>
<td>table 1</td>
</tr>
</table>

<br />
<button onclick="inserttbl2()">Insert</button>
<br />

<table id='tbl2' class='myclass'>
<tr>
<td>table 2</td>
<td>table 2</td>
</tr>
</table>

</body>
</html>

如您所见,tbl2没有 <table id=....>

enter image description here

最佳答案

您可以针对您的情况使用常规的 appendChild,如下所示:

function inserttbl2() {
var table = document.getElementById("tbl1");
var row = table.insertRow(1);
var celltr = row.insertCell(0);
row.appendChild(document.getElementById("tbl2"));
}
.myclass{
background-color: green;
color: white;
}
<!DOCTYPE html>
<html>

<body>

<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>

<table id="tbl1">
<tr>
<td>table 1</td>
<td>table 1</td>
</tr>
<tr>
<td>table 1</td>
<td>table 1</td>
</tr>
</table>

<br />
<button onclick="inserttbl2()">Insert</button>
<br />

<table id='tbl2' class='myclass'>
<tr>
<td>table 2</td>
<td>table 2</td>
</tr>
</table>

</body>
</html>

它将在第一个表格中插入完整的第二个表格。

关于javascript - 在行内插入表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47106227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com