簡體   English   中英

插入表頭 JS

[英]Insert to Table Thead JS

我有一個如下表字段。 我在這里要做的就是使用 javascript 將外部 thead 和值添加到表中。 Thead 標簽永遠不會改變。

<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>

使用 jQuery:

 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>

使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM