Populate html table with javascript array

后端 未结 3 1411
情话喂你
情话喂你 2021-01-21 12:32

I would like to fill an HTML table with a JavaScript array. But, it doesn\'t work and I don\'t know why, my \"innerHTML\" is not interpreted.

My variable co

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 12:59

    You have 3 errors in your code.

    1. You overriding title, link, date and image on each iteration.
    2. You setting only title, I think you want to set all data.
    3. (Posible error) You setting only 1 post into table, probably you want to see them all.

    Easiest (and most common) way to create table from array is build HTML string (with table markup), and append it to table. Unfortunately IE do not support appending html into table, to solve this you may use jquery (it will create Elements from html and append them).

    Example:

    var posts_array = JSON.parse(xhr.responseText);
    var columns = ['title', 'link', 'date', 'image']
    var table_html = '';
    for (var i = 0; i < posts_array.length; i++)
    {
        //create html table row
        table_html += '';
        for( var j = 0; j < columns.length; j++ ){
            //create html table cell, add class to cells to identify columns          
            table_html += '' + posts_array[i][j] + ''
        }
        table_html += ''
    }
    $( "#posts" ).append(  table_html );
    

    Another way is to use table dom api, this will not require jQuery:

    var posts_array = JSON.parse(xhr.responseText);
    var columns = ['title', 'link', 'date', 'image']
    var table = document.getElementById('posts');
    
    for (var i = 0; i < posts_array.length; i++)
    {
        var row = table.insertRow( -1 ); // -1 is insert as last
        for( var j = 0; j < columns.length; j++ ){
            var cell = row.insertCell( - 1 ); // -1 is insert as last
            cell.className = columns[j]; //
            cell.innerHTML = posts_array[i][j]
        }
    }
    

提交回复
热议问题