如何制作一个在Javascript中具有固定列数的表?

时间:2018-07-18 18:24:44

标签: javascript arrays multiple-columns

我的问题是我想让行数自动增加,但是我不确定如何在javascript中设置表的列数。

var x = document.createElement("TABLE");
for (i = 0; i < dataResponse.length; i++) {
    createCell(row.insertCell(i), i, 'row');
}

那我如何在Javascript中设置表的列数?

1 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助。对于内部表,需要重新编写逻辑。

var data = { "issues": [ { "id": "45468", "key": "PR-1968", "fields": { "timetracking": { "originalEstimate": "13h", "remainingEstimate": "13h" }}}, { "id": "45468", "key": "PR-1968", "fields": { "timetracking": { "originalEstimate": "13h", "remainingEstimate": "13h" }}} ]};

function createElement(tagname,content)
{
    var elem = document.createElement(tagname);
    elem.innerHTML = content;
    return elem;
}

function createTable()
{
    var columnnames = Object.keys(data.issues[0]);
    
    var tableheading = "";
    columnnames.forEach(function(columnname){
        tableheading += createElement("th",columnname).outerHTML;
    });
    tableheading = createElement("tr",tableheading).outerHTML;
    
    var tabledata = "";
    data.issues.forEach(function(obj){
        var tablerow = "";
        Object.keys(obj).forEach(function(key){
            var cell = createElement("td",JSON.stringify(obj[key]));
            tablerow += cell.outerHTML;
        });
        tablerow = createElement("tr",tablerow);
        tabledata += tablerow.outerHTML;
    });
    
    return createElement("table",tableheading+tabledata);
}

document.body.appendChild(createTable())
table, tr, th, td
{
    border: 1px solid black;
}