Javascript Effectively Build Table From JSON and Add It to DOM

后端 未结 5 1207
感动是毒
感动是毒 2020-12-09 05:59

I have a JSON array coming in from the server with an array of 200 objects each containing another 10 objects that I want to display in a table format. At first I was creati

5条回答
  •  温柔的废话
    2020-12-09 06:11

    This is definitely do-able. I don't think string concatenation is the way to go. In general it seems to be faster to create elements and manipulate them when they aren't attached to the main DOM; therefore create the entire table first then add it in. In plain javascript I think the code below is basically what you want to achieve..

        //mock up the data (this will come from you AJAX call)..
        var data = [];
        for(var i = 0; i < 200; i++){
            var rowData = [];
            for(var j = 0; j < 10; j++){
                rowData.push("This is a string value");
            }
            data.push(rowData);
        }
    
        //create table..
        var table = document.createElement("table");
        for(var i = 0; i < data.length; i++){
            var rowData = data[i];
            var row = document.createElement("tr");
            for(var j = 0; j < rowData.length; j++){
                var cell = document.createElement("td");
                cell.innerHTML = rowData[j];
                row.appendChild(cell);
            }
            table.appendChild(row);
        }
        //finally append the whole thing..
        document.body.appendChild(table);
    

    When I stick this into the console in Safari, it runs in < 1 second so you should be ok.

提交回复
热议问题