动态创建表列标题

时间:2017-06-18 19:01:02

标签: javascript html-table

现在我无法弄清楚如何为此代码中的所有列添加标头,其中动态创建html表

function createTableAndInsert(sqlArray) {

//create table dynamically - only one row by the moment
var table = document.createElement('table');
for (var i = 1; i < 2; i++) {

    var tr = document.createElement('tr'); // row
    for (var j = 0; j < 8; j++) {

        var td = document.createElement('td'); //column
        var text = document.createTextNode(sqlArray[j]); //cell
        td.appendChild(text);
        tr.appendChild(td);
    }

    table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);

}

3 个答案:

答案 0 :(得分:3)

您可以将标题列表单独传递给您的函数并添加以下代码

$fp = fopen('php://temp', 'w');

答案 1 :(得分:1)

您的结构是:

<tr>
 <td>
   <div></div>
   <div></div>
 </td>
</tr>

thead应该在每行之前附加。

<thead></thead>
<tr>
    <td>
        <div></div>
        <div></div>
    </td>
</tr>

解决方案:

var thead = document.createElement('thead'); thead.innerHTML = 'Header';

table.appendChild(tr);之前,添加此行table.appendChild(thead);

答案 2 :(得分:1)

THEAD需要一个或多个TR元素:

var table = document.createElement('table');  //  'table' may be a reserved word 

var tblHead = document.createElement('thead');
var rowHead = document.createElement('tr');
table.appendChild(tblHead);
tblHead.appendChild(rowHead)
for(j=0; j<8; j++) {
    var celHead = document.createElement('th');
    //the array txtHeaders[] should be passed to your function if you have the values in advance
    // otherwise, you can access the header cells later by:
    // table.getElementsbyTagName('th')[].innerHTML
    celHead.innerHTML = txtHeaders[j]
    rowHead.appendChild(celHead)
}

// now do your row & table loops