2017-11-04 40 views
2

我寫了一個包含兩個表格的腳本: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

回答

1

您可以使用常規的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>

它會在第一個表格中插入第二個表格。

+0

你的答案中的tbl2不是一個正確的位置先生,你可以發送tbl2到div然後插入tbl1請? – Aso