2017-11-04 1 views
2

schrieb ich ein Skript, das zwei Tabellen enthalten: tbl1 ist eine Haupttabelle, tbl2 eine zweite Tabelle, die ich in eine tbl1 zweite Zeile einfügen will durch reine JavaScript verwenden. Es funktioniert perfekt, aber meine tbl2 haben einige html attribute, es nicht zu sehen, wenn ich den Code nach
Notiz eingefügt sehe: tbl1 und tbl2 beide sind gleichen Spaltenkopf und dort haben zwei Spalten.
Tabelle einfügen Innerhalb einer Reihe

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>

Wie Sie sehen, hat die tbl2 nicht haben eine <table id=....>

enter image description here

Antwort

1

Sie die regelmäßige appendChild für Ihren Fall verwenden, wie folgt aus:

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>

Es wird volle zweite Tabelle innerhalb der ersten einfügen.

+0

die tbl2 in Ihrer Antwort ist nicht eine richtige Position Herr, können Sie tbl2 in ein Div senden dann in tbl1 bitte einfügen? – Aso

Verwandte Themen