简体   繁体   English

插入表头 JS

[英]Insert to Table Thead JS

I have a table field like the one below.我有一个如下表字段。 What I want to do exactly here is to add external thead and values to the table with javascript.我在这里要做的就是使用 javascript 将外部 thead 和值添加到表中。 The Thead tag will never change. 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>

How Can add constant thead as below如何添加常量头如下

<thead>
    <tr>
        <th>id</th>
        <th>product_id</th>
        <th>Purchase price</th>
        <th>Sale price</th>
        <th> Stock</th>
    </tr>
</thead>

With jQuery:使用 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>

Use node.insertBefore() :使用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]);

A dirty way but much shorter: put your markup in a string and add it to your table:一种肮脏的方式,但要短得多:将您的标记放在一个字符串中并将其添加到您的表格中:

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