我有一个像下面这样的表字段。 这里我要做的就是用JavaScript将外部的thead和values添加到表中。 头牌永远不会变。
<table id="firm_table">
<tbody>
<tr>
<td>1</td>
<td>31</td>
<td>100</td>
<td>120</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>32</td>
<td>89</td>
<td>102</td>
<td>0</td>
</tr>
</tbody>
</table>
怎样才能增加恒定的头,如下所示
<thead>
<tr>
<th>id</th>
<th>product_id</th>
<th>Purchase price</th>
<th>Sale price</th>
<th> Stock</th>
</tr>
</thead>
使用Node.InsertBefore()
:
var yourTable = document.querySelector("table"); // select your table
var thead = document.createElement("thead");
var row = document.createElement("tr");
var theadCells = ["id", "product_id", "Purchase price", "Sale price", "Stock"];
for(var i = 0; i < theadCells; i++) {
var cell = document.createElement("th");
cell.innerHTML = theadCells[i];
row.appendChild(cell);
}
thead.appendChild(row);
yourTable.insertBefore(thead, yourTable.children[0]);
一种肮脏但短得多的方法:将标记放在一个字符串中,并将其添加到表中:
var thead = "<thead><tr><th>id</th><th>product_id</th><th>Purchase price</th><th>Sale price</th><th>Stock</th></tr></thead>"
yourTable.innerHTML = thead + yourTable.innerHTML;
使用jQuery:
null
const thead = `
<thead>
<tr>
<th>id</th>
<th>product_id</th>
<th>Purchase price</th>
<th>Sale price</th>
<th> Stock</th>
</tr>
</thead>`;
$('#firm_table').prepend(thead);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="firm_table">
<tbody>
<tr>
<td>1</td>
<td>31</td>
<td>100</td>
<td>120</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>32</td>
<td>89</td>
<td>102</td>
<td>0</td>
</tr>
</tbody>
</table>